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
|
---|---|---|---|---|---|---|---|---|
10068350 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextArea.
/// </summary>
public static SearchPanel Install(TextArea textArea)
{
if (textArea == null) throw new ArgumentNullException(nameof(textArea));
var panel = new SearchPanel();
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// </summary>
public void Uninstall()
{
CloseAndRemove();
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
_textArea.Focus();
}
/// <summary>
/// Closes the SearchPanel and removes it.
/// </summary>
private void CloseAndRemove()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> feature netcore3 support #168
https://github.com/icsharpcode/AvalonEdit/pull/168/ (partial) TextDocument changes will be updated separately.
<DFF> @@ -240,7 +240,10 @@ namespace AvaloniaEdit.Search
/// </summary>
public void Uninstall()
{
- CloseAndRemove();
+ Close();
+ _textArea.DocumentChanged -= TextArea_DocumentChanged;
+ if (_currentDocument != null)
+ _currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
@@ -490,17 +493,6 @@ namespace AvaloniaEdit.Search
_textArea.Focus();
}
- /// <summary>
- /// Closes the SearchPanel and removes it.
- /// </summary>
- private void CloseAndRemove()
- {
- Close();
- _textArea.DocumentChanged -= TextArea_DocumentChanged;
- if (_currentDocument != null)
- _currentDocument.TextChanged -= TextArea_Document_TextChanged;
- }
-
/// <summary>
/// Opens the an existing search panel.
/// </summary>
| 4 | feature netcore3 support #168 | 12 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068351 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextArea.
/// </summary>
public static SearchPanel Install(TextArea textArea)
{
if (textArea == null) throw new ArgumentNullException(nameof(textArea));
var panel = new SearchPanel();
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// </summary>
public void Uninstall()
{
CloseAndRemove();
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
_textArea.Focus();
}
/// <summary>
/// Closes the SearchPanel and removes it.
/// </summary>
private void CloseAndRemove()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> feature netcore3 support #168
https://github.com/icsharpcode/AvalonEdit/pull/168/ (partial) TextDocument changes will be updated separately.
<DFF> @@ -240,7 +240,10 @@ namespace AvaloniaEdit.Search
/// </summary>
public void Uninstall()
{
- CloseAndRemove();
+ Close();
+ _textArea.DocumentChanged -= TextArea_DocumentChanged;
+ if (_currentDocument != null)
+ _currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
@@ -490,17 +493,6 @@ namespace AvaloniaEdit.Search
_textArea.Focus();
}
- /// <summary>
- /// Closes the SearchPanel and removes it.
- /// </summary>
- private void CloseAndRemove()
- {
- Close();
- _textArea.DocumentChanged -= TextArea_DocumentChanged;
- if (_currentDocument != null)
- _currentDocument.TextChanged -= TextArea_Document_TextChanged;
- }
-
/// <summary>
/// Opens the an existing search panel.
/// </summary>
| 4 | feature netcore3 support #168 | 12 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068352 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextArea.
/// </summary>
public static SearchPanel Install(TextArea textArea)
{
if (textArea == null) throw new ArgumentNullException(nameof(textArea));
var panel = new SearchPanel();
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// </summary>
public void Uninstall()
{
CloseAndRemove();
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
_textArea.Focus();
}
/// <summary>
/// Closes the SearchPanel and removes it.
/// </summary>
private void CloseAndRemove()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> feature netcore3 support #168
https://github.com/icsharpcode/AvalonEdit/pull/168/ (partial) TextDocument changes will be updated separately.
<DFF> @@ -240,7 +240,10 @@ namespace AvaloniaEdit.Search
/// </summary>
public void Uninstall()
{
- CloseAndRemove();
+ Close();
+ _textArea.DocumentChanged -= TextArea_DocumentChanged;
+ if (_currentDocument != null)
+ _currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
@@ -490,17 +493,6 @@ namespace AvaloniaEdit.Search
_textArea.Focus();
}
- /// <summary>
- /// Closes the SearchPanel and removes it.
- /// </summary>
- private void CloseAndRemove()
- {
- Close();
- _textArea.DocumentChanged -= TextArea_DocumentChanged;
- if (_currentDocument != null)
- _currentDocument.TextChanged -= TextArea_Document_TextChanged;
- }
-
/// <summary>
/// Opens the an existing search panel.
/// </summary>
| 4 | feature netcore3 support #168 | 12 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068353 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextArea.
/// </summary>
public static SearchPanel Install(TextArea textArea)
{
if (textArea == null) throw new ArgumentNullException(nameof(textArea));
var panel = new SearchPanel();
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// </summary>
public void Uninstall()
{
CloseAndRemove();
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
_textArea.Focus();
}
/// <summary>
/// Closes the SearchPanel and removes it.
/// </summary>
private void CloseAndRemove()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> feature netcore3 support #168
https://github.com/icsharpcode/AvalonEdit/pull/168/ (partial) TextDocument changes will be updated separately.
<DFF> @@ -240,7 +240,10 @@ namespace AvaloniaEdit.Search
/// </summary>
public void Uninstall()
{
- CloseAndRemove();
+ Close();
+ _textArea.DocumentChanged -= TextArea_DocumentChanged;
+ if (_currentDocument != null)
+ _currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
@@ -490,17 +493,6 @@ namespace AvaloniaEdit.Search
_textArea.Focus();
}
- /// <summary>
- /// Closes the SearchPanel and removes it.
- /// </summary>
- private void CloseAndRemove()
- {
- Close();
- _textArea.DocumentChanged -= TextArea_DocumentChanged;
- if (_currentDocument != null)
- _currentDocument.TextChanged -= TextArea_Document_TextChanged;
- }
-
/// <summary>
/// Opens the an existing search panel.
/// </summary>
| 4 | feature netcore3 support #168 | 12 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068354 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextArea.
/// </summary>
public static SearchPanel Install(TextArea textArea)
{
if (textArea == null) throw new ArgumentNullException(nameof(textArea));
var panel = new SearchPanel();
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// </summary>
public void Uninstall()
{
CloseAndRemove();
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
_textArea.Focus();
}
/// <summary>
/// Closes the SearchPanel and removes it.
/// </summary>
private void CloseAndRemove()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> feature netcore3 support #168
https://github.com/icsharpcode/AvalonEdit/pull/168/ (partial) TextDocument changes will be updated separately.
<DFF> @@ -240,7 +240,10 @@ namespace AvaloniaEdit.Search
/// </summary>
public void Uninstall()
{
- CloseAndRemove();
+ Close();
+ _textArea.DocumentChanged -= TextArea_DocumentChanged;
+ if (_currentDocument != null)
+ _currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
@@ -490,17 +493,6 @@ namespace AvaloniaEdit.Search
_textArea.Focus();
}
- /// <summary>
- /// Closes the SearchPanel and removes it.
- /// </summary>
- private void CloseAndRemove()
- {
- Close();
- _textArea.DocumentChanged -= TextArea_DocumentChanged;
- if (_currentDocument != null)
- _currentDocument.TextChanged -= TextArea_Document_TextChanged;
- }
-
/// <summary>
/// Opens the an existing search panel.
/// </summary>
| 4 | feature netcore3 support #168 | 12 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068355 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextArea.
/// </summary>
public static SearchPanel Install(TextArea textArea)
{
if (textArea == null) throw new ArgumentNullException(nameof(textArea));
var panel = new SearchPanel();
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// </summary>
public void Uninstall()
{
CloseAndRemove();
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
_textArea.Focus();
}
/// <summary>
/// Closes the SearchPanel and removes it.
/// </summary>
private void CloseAndRemove()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> feature netcore3 support #168
https://github.com/icsharpcode/AvalonEdit/pull/168/ (partial) TextDocument changes will be updated separately.
<DFF> @@ -240,7 +240,10 @@ namespace AvaloniaEdit.Search
/// </summary>
public void Uninstall()
{
- CloseAndRemove();
+ Close();
+ _textArea.DocumentChanged -= TextArea_DocumentChanged;
+ if (_currentDocument != null)
+ _currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
@@ -490,17 +493,6 @@ namespace AvaloniaEdit.Search
_textArea.Focus();
}
- /// <summary>
- /// Closes the SearchPanel and removes it.
- /// </summary>
- private void CloseAndRemove()
- {
- Close();
- _textArea.DocumentChanged -= TextArea_DocumentChanged;
- if (_currentDocument != null)
- _currentDocument.TextChanged -= TextArea_Document_TextChanged;
- }
-
/// <summary>
/// Opens the an existing search panel.
/// </summary>
| 4 | feature netcore3 support #168 | 12 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068356 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextArea.
/// </summary>
public static SearchPanel Install(TextArea textArea)
{
if (textArea == null) throw new ArgumentNullException(nameof(textArea));
var panel = new SearchPanel();
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// </summary>
public void Uninstall()
{
CloseAndRemove();
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
_textArea.Focus();
}
/// <summary>
/// Closes the SearchPanel and removes it.
/// </summary>
private void CloseAndRemove()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> feature netcore3 support #168
https://github.com/icsharpcode/AvalonEdit/pull/168/ (partial) TextDocument changes will be updated separately.
<DFF> @@ -240,7 +240,10 @@ namespace AvaloniaEdit.Search
/// </summary>
public void Uninstall()
{
- CloseAndRemove();
+ Close();
+ _textArea.DocumentChanged -= TextArea_DocumentChanged;
+ if (_currentDocument != null)
+ _currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
@@ -490,17 +493,6 @@ namespace AvaloniaEdit.Search
_textArea.Focus();
}
- /// <summary>
- /// Closes the SearchPanel and removes it.
- /// </summary>
- private void CloseAndRemove()
- {
- Close();
- _textArea.DocumentChanged -= TextArea_DocumentChanged;
- if (_currentDocument != null)
- _currentDocument.TextChanged -= TextArea_Document_TextChanged;
- }
-
/// <summary>
/// Opens the an existing search panel.
/// </summary>
| 4 | feature netcore3 support #168 | 12 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068357 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextArea.
/// </summary>
public static SearchPanel Install(TextArea textArea)
{
if (textArea == null) throw new ArgumentNullException(nameof(textArea));
var panel = new SearchPanel();
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// </summary>
public void Uninstall()
{
CloseAndRemove();
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
_textArea.Focus();
}
/// <summary>
/// Closes the SearchPanel and removes it.
/// </summary>
private void CloseAndRemove()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> feature netcore3 support #168
https://github.com/icsharpcode/AvalonEdit/pull/168/ (partial) TextDocument changes will be updated separately.
<DFF> @@ -240,7 +240,10 @@ namespace AvaloniaEdit.Search
/// </summary>
public void Uninstall()
{
- CloseAndRemove();
+ Close();
+ _textArea.DocumentChanged -= TextArea_DocumentChanged;
+ if (_currentDocument != null)
+ _currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
@@ -490,17 +493,6 @@ namespace AvaloniaEdit.Search
_textArea.Focus();
}
- /// <summary>
- /// Closes the SearchPanel and removes it.
- /// </summary>
- private void CloseAndRemove()
- {
- Close();
- _textArea.DocumentChanged -= TextArea_DocumentChanged;
- if (_currentDocument != null)
- _currentDocument.TextChanged -= TextArea_Document_TextChanged;
- }
-
/// <summary>
/// Opens the an existing search panel.
/// </summary>
| 4 | feature netcore3 support #168 | 12 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068358 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextArea.
/// </summary>
public static SearchPanel Install(TextArea textArea)
{
if (textArea == null) throw new ArgumentNullException(nameof(textArea));
var panel = new SearchPanel();
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// </summary>
public void Uninstall()
{
CloseAndRemove();
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
_textArea.Focus();
}
/// <summary>
/// Closes the SearchPanel and removes it.
/// </summary>
private void CloseAndRemove()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> feature netcore3 support #168
https://github.com/icsharpcode/AvalonEdit/pull/168/ (partial) TextDocument changes will be updated separately.
<DFF> @@ -240,7 +240,10 @@ namespace AvaloniaEdit.Search
/// </summary>
public void Uninstall()
{
- CloseAndRemove();
+ Close();
+ _textArea.DocumentChanged -= TextArea_DocumentChanged;
+ if (_currentDocument != null)
+ _currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
@@ -490,17 +493,6 @@ namespace AvaloniaEdit.Search
_textArea.Focus();
}
- /// <summary>
- /// Closes the SearchPanel and removes it.
- /// </summary>
- private void CloseAndRemove()
- {
- Close();
- _textArea.DocumentChanged -= TextArea_DocumentChanged;
- if (_currentDocument != null)
- _currentDocument.TextChanged -= TextArea_Document_TextChanged;
- }
-
/// <summary>
/// Opens the an existing search panel.
/// </summary>
| 4 | feature netcore3 support #168 | 12 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068359 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextArea.
/// </summary>
public static SearchPanel Install(TextArea textArea)
{
if (textArea == null) throw new ArgumentNullException(nameof(textArea));
var panel = new SearchPanel();
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// </summary>
public void Uninstall()
{
CloseAndRemove();
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
_textArea.Focus();
}
/// <summary>
/// Closes the SearchPanel and removes it.
/// </summary>
private void CloseAndRemove()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> feature netcore3 support #168
https://github.com/icsharpcode/AvalonEdit/pull/168/ (partial) TextDocument changes will be updated separately.
<DFF> @@ -240,7 +240,10 @@ namespace AvaloniaEdit.Search
/// </summary>
public void Uninstall()
{
- CloseAndRemove();
+ Close();
+ _textArea.DocumentChanged -= TextArea_DocumentChanged;
+ if (_currentDocument != null)
+ _currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
@@ -490,17 +493,6 @@ namespace AvaloniaEdit.Search
_textArea.Focus();
}
- /// <summary>
- /// Closes the SearchPanel and removes it.
- /// </summary>
- private void CloseAndRemove()
- {
- Close();
- _textArea.DocumentChanged -= TextArea_DocumentChanged;
- if (_currentDocument != null)
- _currentDocument.TextChanged -= TextArea_Document_TextChanged;
- }
-
/// <summary>
/// Opens the an existing search panel.
/// </summary>
| 4 | feature netcore3 support #168 | 12 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068360 | <NME> SearchPanel.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.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Rendering;
namespace AvaloniaEdit.Search
{
/// <summary>
/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
/// </summary>
public class SearchPanel : TemplatedControl, IRoutedCommandBindable
{
private TextArea _textArea;
private SearchInputHandler _handler;
private TextDocument _currentDocument;
private SearchResultBackgroundRenderer _renderer;
private TextBox _searchTextBox;
private TextEditor _textEditor { get; set; }
private Border _border;
#region DependencyProperties
/// <summary>
/// Dependency property for <see cref="UseRegex"/>.
/// </summary>
public static readonly StyledProperty<bool> UseRegexProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(UseRegex));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex
{
get => GetValue(UseRegexProperty);
set => SetValue(UseRegexProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MatchCase"/>.
/// </summary>
public static readonly StyledProperty<bool> MatchCaseProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(MatchCase));
/// <summary>
/// Gets/sets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase
{
get => GetValue(MatchCaseProperty);
set => SetValue(MatchCaseProperty, value);
}
/// <summary>
/// Dependency property for <see cref="WholeWords"/>.
/// </summary>
public static readonly StyledProperty<bool> WholeWordsProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(WholeWords));
/// <summary>
/// Gets/sets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords
{
get => GetValue(WholeWordsProperty);
set => SetValue(WholeWordsProperty, value);
}
/// <summary>
/// Dependency property for <see cref="SearchPattern"/>.
/// </summary>
public static readonly StyledProperty<string> SearchPatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(SearchPattern), "");
/// <summary>
/// Gets/sets the search pattern.
/// </summary>
public string SearchPattern
{
get => GetValue(SearchPatternProperty);
set => SetValue(SearchPatternProperty, value);
}
public static readonly StyledProperty<bool> IsReplaceModeProperty =
AvaloniaProperty.Register<SearchPanel, bool>(nameof(IsReplaceMode));
/// <summary>
/// Checks if replacemode is allowed
/// </summary>
/// <returns>False if editor is not null and readonly</returns>
private static bool ValidateReplaceMode(SearchPanel panel, bool v1)
{
if (panel._textEditor == null || !v1) return v1;
return !panel._textEditor.IsReadOnly;
}
public bool IsReplaceMode
{
get => GetValue(IsReplaceModeProperty);
set => SetValue(IsReplaceModeProperty, _textEditor?.IsReadOnly ?? false ? false : value);
}
public static readonly StyledProperty<string> ReplacePatternProperty =
AvaloniaProperty.Register<SearchPanel, string>(nameof(ReplacePattern));
public string ReplacePattern
{
get => GetValue(ReplacePatternProperty);
set => SetValue(ReplacePatternProperty, value);
}
/// <summary>
/// Dependency property for <see cref="MarkerBrush"/>.
/// </summary>
public static readonly StyledProperty<IBrush> MarkerBrushProperty =
AvaloniaProperty.Register<SearchPanel, IBrush>(nameof(MarkerBrush), Brushes.LightGreen);
/// <summary>
/// Gets/sets the Brush used for marking search results in the TextView.
/// </summary>
public IBrush MarkerBrush
{
get => GetValue(MarkerBrushProperty);
set => SetValue(MarkerBrushProperty, value);
}
#endregion
private static void MarkerBrushChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel._renderer.MarkerBrush = (IBrush)e.NewValue;
}
}
private ISearchStrategy _strategy;
private static void SearchPatternChangedCallback(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is SearchPanel panel)
{
panel.ValidateSearchText();
panel.UpdateSearch();
}
}
private void UpdateSearch()
{
// only reset as long as there are results
// if no results are found, the "no matches found" message should not flicker.
// if results are found by the next run, the message will be hidden inside DoSearch ...
if (_renderer.CurrentResults.Any())
_messageView.IsOpen = false;
_strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
DoSearch(true);
}
static SearchPanel()
{
UseRegexProperty.Changed.Subscribe(SearchPatternChangedCallback);
MatchCaseProperty.Changed.Subscribe(SearchPatternChangedCallback);
WholeWordsProperty.Changed.Subscribe(SearchPatternChangedCallback);
SearchPatternProperty.Changed.Subscribe(SearchPatternChangedCallback);
MarkerBrushProperty.Changed.Subscribe(MarkerBrushChangedCallback);
}
/// <summary>
/// Creates a new SearchPanel.
/// </summary>
private SearchPanel()
{
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
/// </summary>
/// <remarks>This is a convenience wrapper.</remarks>
public static SearchPanel Install(TextEditor editor)
{
if (editor == null) throw new ArgumentNullException(nameof(editor));
SearchPanel searchPanel = Install(editor.TextArea);
searchPanel._textEditor = editor;
return searchPanel;
}
/// <summary>
/// Creates a SearchPanel and installs it to the TextArea.
/// </summary>
public static SearchPanel Install(TextArea textArea)
{
if (textArea == null) throw new ArgumentNullException(nameof(textArea));
var panel = new SearchPanel();
panel.AttachInternal(textArea);
panel._handler = new SearchInputHandler(textArea, panel);
textArea.DefaultInputHandler.NestedInputHandlers.Add(panel._handler);
((ISetLogicalParent)panel).SetParent(textArea);
return panel;
}
/// <summary>
/// Adds the commands used by SearchPanel to the given CommandBindingCollection.
/// </summary>
public void RegisterCommands(ICollection<RoutedCommandBinding> commandBindings)
{
_handler.RegisterGlobalCommands(commandBindings);
}
/// <summary>
/// </summary>
public void Uninstall()
{
CloseAndRemove();
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
private void AttachInternal(TextArea textArea)
{
_textArea = textArea;
_renderer = new SearchResultBackgroundRenderer();
_currentDocument = textArea.Document;
if (_currentDocument != null)
_currentDocument.TextChanged += TextArea_Document_TextChanged;
textArea.DocumentChanged += TextArea_DocumentChanged;
KeyDown += SearchLayerKeyDown;
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Find, (sender, e) =>
{
IsReplaceMode = false;
Reactivate();
}));
CommandBindings.Add(new RoutedCommandBinding(ApplicationCommands.Replace, (sender, e) => IsReplaceMode = true));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceNext, (sender, e) => ReplaceNext(), (sender, e) => e.CanExecute = IsReplaceMode));
CommandBindings.Add(new RoutedCommandBinding(SearchCommands.ReplaceAll, (sender, e) => ReplaceAll(), (sender, e) => e.CanExecute = IsReplaceMode));
IsClosed = true;
}
private void TextArea_DocumentChanged(object sender, EventArgs e)
{
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
_currentDocument = _textArea.Document;
if (_currentDocument != null)
{
_currentDocument.TextChanged += TextArea_Document_TextChanged;
DoSearch(false);
}
}
private void TextArea_Document_TextChanged(object sender, EventArgs e)
{
DoSearch(false);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
_border = e.NameScope.Find<Border>("PART_Border");
_searchTextBox = e.NameScope.Find<TextBox>("PART_searchTextBox");
_messageView = e.NameScope.Find<Popup>("PART_MessageView");
_messageViewContent = e.NameScope.Find<ContentPresenter>("PART_MessageContent");
}
private void ValidateSearchText()
{
if (_searchTextBox == null)
return;
try
{
UpdateSearch();
_validationError = null;
}
catch (SearchPatternException ex)
{
_validationError = ex.Message;
}
}
/// <summary>
/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
/// </summary>
public void Reactivate()
{
if (_searchTextBox == null)
return;
_searchTextBox.Focus();
_searchTextBox.SelectionStart = 0;
_searchTextBox.SelectionEnd = _searchTextBox.Text?.Length ?? 0;
}
/// <summary>
/// Moves to the next occurrence in the file.
/// </summary>
public void FindNext()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset + 1) ??
_renderer.CurrentResults.FirstSegment;
if (result != null)
{
SelectResult(result);
}
}
/// <summary>
/// Moves to the previous occurrence in the file.
/// </summary>
public void FindPrevious()
{
var result = _renderer.CurrentResults.FindFirstSegmentWithStartAfter(_textArea.Caret.Offset);
if (result != null)
result = _renderer.CurrentResults.GetPreviousSegment(result);
if (result == null)
result = _renderer.CurrentResults.LastSegment;
if (result != null)
{
SelectResult(result);
}
}
public void ReplaceNext()
{
if (!IsReplaceMode) return;
FindNext();
if (!_textArea.Selection.IsEmpty)
{
_textArea.Selection.ReplaceSelectionWithText(ReplacePattern ?? string.Empty);
}
UpdateSearch();
}
public void ReplaceAll()
{
if (!IsReplaceMode) return;
var replacement = ReplacePattern ?? string.Empty;
var document = _textArea.Document;
using (document.RunUpdate())
{
var segments = _renderer.CurrentResults.OrderByDescending(x => x.EndOffset).ToArray();
foreach (var textSegment in segments)
{
document.Replace(textSegment.StartOffset, textSegment.Length,
new StringTextSource(replacement));
}
}
}
private Popup _messageView;
private ContentPresenter _messageViewContent;
private string _validationError;
private void DoSearch(bool changeSelection)
{
if (IsClosed)
return;
_renderer.CurrentResults.Clear();
if (!string.IsNullOrEmpty(SearchPattern))
{
var offset = _textArea.Caret.Offset;
if (changeSelection)
{
_textArea.ClearSelection();
}
// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
foreach (var result in _strategy.FindAll(_textArea.Document, 0, _textArea.Document.TextLength).Cast<SearchResult>())
{
if (changeSelection && result.StartOffset >= offset)
{
SelectResult(result);
changeSelection = false;
}
_renderer.CurrentResults.Add(result);
}
}
if (_messageView != null)
{
if (!_renderer.CurrentResults.Any())
{
_messageViewContent.Content = SR.SearchNoMatchesFoundText;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
else
_messageView.IsOpen = false;
}
_textArea.TextView.InvalidateLayer(KnownLayer.Selection);
}
private void SelectResult(TextSegment result)
{
_textArea.Caret.Offset = result.StartOffset;
_textArea.Selection = Selection.Create(_textArea, result.StartOffset, result.EndOffset);
double distanceToViewBorder = _border == null ?
Caret.MinimumDistanceToViewBorder :
_border.Bounds.Height + _textArea.TextView.DefaultLineHeight;
_textArea.Caret.BringCaretToView(distanceToViewBorder);
// show caret even if the editor does not have the Keyboard Focus
_textArea.Caret.Show();
}
private void SearchLayerKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Enter:
e.Handled = true;
if (e.KeyModifiers.HasFlag(KeyModifiers.Shift))
{
FindPrevious();
}
else
{
FindNext();
}
if (_searchTextBox != null)
{
if (_validationError != null)
{
_messageViewContent.Content = SR.SearchErrorText + " " + _validationError;
_messageView.PlacementTarget = _searchTextBox;
_messageView.IsOpen = true;
}
}
break;
case Key.Escape:
e.Handled = true;
Close();
break;
}
}
/// <summary>
/// Gets whether the Panel is already closed.
/// </summary>
public bool IsClosed { get; private set; }
/// <summary>
/// Gets whether the Panel is currently opened.
/// </summary>
public bool IsOpened => !IsClosed;
/// <summary>
/// Closes the SearchPanel.
_textArea.Focus();
}
/// <summary>
/// Closes the SearchPanel and removes it.
/// </summary>
private void CloseAndRemove()
{
Close();
_textArea.DocumentChanged -= TextArea_DocumentChanged;
if (_currentDocument != null)
_currentDocument.TextChanged -= TextArea_Document_TextChanged;
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
IsClosed = true;
// Clear existing search results so that the segments don't have to be maintained
_renderer.CurrentResults.Clear();
_textArea.Focus();
}
/// <summary>
/// Opens the an existing search panel.
/// </summary>
public void Open()
{
if (!IsClosed) return;
_textArea.AddChild(this);
_textArea.TextView.BackgroundRenderers.Add(_renderer);
IsClosed = false;
DoSearch(false);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
e.Handled = true;
base.OnPointerPressed(e);
}
protected override void OnPointerMoved(PointerEventArgs e)
{
Cursor = Cursor.Default;
base.OnPointerMoved(e);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
e.Handled = true;
base.OnGotFocus(e);
}
/// <summary>
/// Fired when SearchOptions are changed inside the SearchPanel.
/// </summary>
public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
/// <summary>
/// Raises the <see cref="SearchOptionsChanged" /> event.
/// </summary>
protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
{
SearchOptionsChanged?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
}
/// <summary>
/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
/// </summary>
public class SearchOptionsChangedEventArgs : EventArgs
{
/// <summary>
/// Gets the search pattern.
/// </summary>
public string SearchPattern { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted case-sensitive.
/// </summary>
public bool MatchCase { get; }
/// <summary>
/// Gets whether the search pattern should be interpreted as regular expression.
/// </summary>
public bool UseRegex { get; }
/// <summary>
/// Gets whether the search pattern should only match whole words.
/// </summary>
public bool WholeWords { get; }
/// <summary>
/// Creates a new SearchOptionsChangedEventArgs instance.
/// </summary>
public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
{
SearchPattern = searchPattern;
MatchCase = matchCase;
UseRegex = useRegex;
WholeWords = wholeWords;
}
}
}
<MSG> feature netcore3 support #168
https://github.com/icsharpcode/AvalonEdit/pull/168/ (partial) TextDocument changes will be updated separately.
<DFF> @@ -240,7 +240,10 @@ namespace AvaloniaEdit.Search
/// </summary>
public void Uninstall()
{
- CloseAndRemove();
+ Close();
+ _textArea.DocumentChanged -= TextArea_DocumentChanged;
+ if (_currentDocument != null)
+ _currentDocument.TextChanged -= TextArea_Document_TextChanged;
_textArea.DefaultInputHandler.NestedInputHandlers.Remove(_handler);
}
@@ -490,17 +493,6 @@ namespace AvaloniaEdit.Search
_textArea.Focus();
}
- /// <summary>
- /// Closes the SearchPanel and removes it.
- /// </summary>
- private void CloseAndRemove()
- {
- Close();
- _textArea.DocumentChanged -= TextArea_DocumentChanged;
- if (_currentDocument != null)
- _currentDocument.TextChanged -= TextArea_Document_TextChanged;
- }
-
/// <summary>
/// Opens the an existing search panel.
/// </summary>
| 4 | feature netcore3 support #168 | 12 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068361 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068362 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068363 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068364 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068365 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068366 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068367 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068368 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068369 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068370 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068371 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068372 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068373 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068374 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068375 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void SetDocumentToNull()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
[Test]
public void CheckEventOrderOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Remove redundant tests
<DFF> @@ -33,7 +33,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -53,7 +54,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -73,7 +75,8 @@ namespace AvaloniaEdit.Editing
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform(),
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
- fontManagerImpl: new MockFontManagerImpl())))
+ fontManagerImpl: new MockFontManagerImpl(),
+ textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Remove redundant tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10068376 | <NME> el.js
<BEF> ADDFILE
<MSG> Greek translation
Greek translation file.
<DFF> @@ -0,0 +1,46 @@
+(function(jsGrid) {
+
+ jsGrid.locales.el = {
+ grid: {
+ noDataContent: "Δεν βρέθηκαν δεδομένα",
+ deleteConfirm: "Θέλετε σίγουρα να κάνετε οριστική διαγραφή των δεδομένων;",
+ pagerFormat: "Σελίδες: {first} {prev} {pages} {next} {last} {pageIndex} από {pageCount}",
+ pagePrevText: "<",
+ pageNextText: ">",
+ pageFirstText: "<<",
+ pageLastText: ">>",
+ loadMessage: "Παρακαλώ περιμένετε...",
+ invalidMessage: "Η τιμή που δώσατε δεν είναι έγκυρη!"
+ },
+
+ loadIndicator: {
+ message: "Φόρτωση..."
+ },
+
+ fields: {
+ control: {
+ searchModeButtonTooltip: "Αναζήτηση",
+ insertModeButtonTooltip: "Εισάγετε φίλτρο",
+ editButtonTooltip: "Επεξεργασία",
+ deleteButtonTooltip: "Διαγραφή",
+ searchButtonTooltip: "Εύρεση",
+ clearFilterButtonTooltip: "Αφαίρεση φίλτρου",
+ insertButtonTooltip: "Εισαγωγή",
+ updateButtonTooltip: "Αποθήκευση",
+ cancelEditButtonTooltip: "Ακύρωση"
+ }
+ },
+
+ validators: {
+ required: { message: "Είναι υποχρεωτικό πεδίο" },
+ rangeLength: { message: "Το πλήθος των χαρακτήρων είναι εκτός των αποδεκτών ορίων" },
+ minLength: { message: "Το πλήθος των χαρακτήρων είναι μικρότερο το ορίου" },
+ maxLength: { message: "Το πλήθος των χαρακτήρων ξεπερνάει το όριο" },
+ pattern: { message: "Η τιμή που δώσατε δεν είναι έγκυρη" },
+ range: { message: "Η τιμή που δώσατε είναι εκτός των αποδεκτών ορίων" },
+ min: { message: "Η τιμή που δώσατε είναι πολύ μικρή" },
+ max: { message: "Η τιμή που δώσατε είναι πολύ μεγάλη" }
+ }
+ };
+
+}(jsGrid, jQuery));
| 46 | Greek translation | 0 | .js | js | mit | tabalinas/jsgrid |
10068377 | <NME> el.js
<BEF> ADDFILE
<MSG> Greek translation
Greek translation file.
<DFF> @@ -0,0 +1,46 @@
+(function(jsGrid) {
+
+ jsGrid.locales.el = {
+ grid: {
+ noDataContent: "Δεν βρέθηκαν δεδομένα",
+ deleteConfirm: "Θέλετε σίγουρα να κάνετε οριστική διαγραφή των δεδομένων;",
+ pagerFormat: "Σελίδες: {first} {prev} {pages} {next} {last} {pageIndex} από {pageCount}",
+ pagePrevText: "<",
+ pageNextText: ">",
+ pageFirstText: "<<",
+ pageLastText: ">>",
+ loadMessage: "Παρακαλώ περιμένετε...",
+ invalidMessage: "Η τιμή που δώσατε δεν είναι έγκυρη!"
+ },
+
+ loadIndicator: {
+ message: "Φόρτωση..."
+ },
+
+ fields: {
+ control: {
+ searchModeButtonTooltip: "Αναζήτηση",
+ insertModeButtonTooltip: "Εισάγετε φίλτρο",
+ editButtonTooltip: "Επεξεργασία",
+ deleteButtonTooltip: "Διαγραφή",
+ searchButtonTooltip: "Εύρεση",
+ clearFilterButtonTooltip: "Αφαίρεση φίλτρου",
+ insertButtonTooltip: "Εισαγωγή",
+ updateButtonTooltip: "Αποθήκευση",
+ cancelEditButtonTooltip: "Ακύρωση"
+ }
+ },
+
+ validators: {
+ required: { message: "Είναι υποχρεωτικό πεδίο" },
+ rangeLength: { message: "Το πλήθος των χαρακτήρων είναι εκτός των αποδεκτών ορίων" },
+ minLength: { message: "Το πλήθος των χαρακτήρων είναι μικρότερο το ορίου" },
+ maxLength: { message: "Το πλήθος των χαρακτήρων ξεπερνάει το όριο" },
+ pattern: { message: "Η τιμή που δώσατε δεν είναι έγκυρη" },
+ range: { message: "Η τιμή που δώσατε είναι εκτός των αποδεκτών ορίων" },
+ min: { message: "Η τιμή που δώσατε είναι πολύ μικρή" },
+ max: { message: "Η τιμή που δώσατε είναι πολύ μεγάλη" }
+ }
+ };
+
+}(jsGrid, jQuery));
| 46 | Greek translation | 0 | .js | js | mit | tabalinas/jsgrid |
10068378 | <NME> jsgrid.core.js
<BEF> (function(window, $, undefined) {
var JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID,
JSGRID_ROW_DATA_KEY = "JSGridItem",
JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow",
SORT_ORDER_ASC = "asc",
SORT_ORDER_DESC = "desc",
FIRST_PAGE_PLACEHOLDER = "{first}",
PAGES_PLACEHOLDER = "{pages}",
PREV_PAGE_PLACEHOLDER = "{prev}",
NEXT_PAGE_PLACEHOLDER = "{next}",
LAST_PAGE_PLACEHOLDER = "{last}",
PAGE_INDEX_PLACEHOLDER = "{pageIndex}",
PAGE_COUNT_PLACEHOLDER = "{pageCount}",
ITEM_COUNT_PLACEHOLDER = "{itemCount}",
EMPTY_HREF = "javascript:void(0);";
var getOrApply = function(value, context) {
if($.isFunction(value)) {
return value.apply(context, $.makeArray(arguments).slice(2));
}
return value;
};
var normalizePromise = function(promise) {
var d = $.Deferred();
if(promise && promise.then) {
promise.then(function() {
d.resolve.apply(d, arguments);
}, function() {
d.reject.apply(d, arguments);
});
} else {
d.resolve(promise);
}
return d.promise();
};
var defaultController = {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
};
function Grid(element, config) {
var $element = $(element);
$element.data(JSGRID_DATA_KEY, this);
this._container = $element;
this.data = [];
this.fields = [];
this._editingRow = null;
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._firstDisplayingPage = 1;
this._init(config);
this.render();
}
Grid.prototype = {
width: "auto",
height: "auto",
updateOnResize: true,
rowClass: $.noop,
rowRenderer: null,
rowClick: function(args) {
if(this.editing) {
this.editItem($(args.event.target).closest("tr"));
}
},
rowDoubleClick: $.noop,
noDataContent: "Not found",
noDataRowClass: "jsgrid-nodata-row",
heading: true,
headerRowRenderer: null,
headerRowClass: "jsgrid-header-row",
headerCellClass: "jsgrid-header-cell",
filtering: false,
filterRowRenderer: null,
filterRowClass: "jsgrid-filter-row",
inserting: false,
insertRowLocation: "bottom",
insertRowRenderer: null,
insertRowClass: "jsgrid-insert-row",
editing: false,
editRowRenderer: null,
editRowClass: "jsgrid-edit-row",
confirmDeleting: true,
deleteConfirm: "Are you sure?",
selecting: true,
selectedRowClass: "jsgrid-selected-row",
oddRowClass: "jsgrid-row",
evenRowClass: "jsgrid-alt-row",
cellClass: "jsgrid-cell",
sorting: false,
sortableClass: "jsgrid-header-sortable",
sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc",
sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc",
paging: false,
pagerContainer: null,
pageIndex: 1,
pageSize: 20,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
pagerContainerClass: "jsgrid-pager-container",
pagerClass: "jsgrid-pager",
pagerNavButtonClass: "jsgrid-pager-nav-button",
pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button",
pageClass: "jsgrid-pager-page",
currentPageClass: "jsgrid-pager-current-page",
customLoading: false,
pageLoading: false,
autoload: false,
controller: defaultController,
loadIndication: true,
loadIndicationDelay: 500,
loadMessage: "Please, wait...",
this._initController();
this._initLoadIndicator();
this._initFields();
if(this.updateOnResize) {
this._attachWindowResizeCallback();
}
window.alert([this.invalidMessage].concat(messages).join("\n"));
},
onInit: $.noop,
onRefreshing: $.noop,
onRefreshed: $.noop,
onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
onItemInserted: $.noop,
onItemEditing: $.noop,
onItemEditCancelling: $.noop,
onItemUpdating: $.noop,
onItemUpdated: $.noop,
onItemInvalid: $.noop,
onDataLoading: $.noop,
onDataLoaded: $.noop,
onDataExporting: $.noop,
onOptionChanging: $.noop,
onOptionChanged: $.noop,
onError: $.noop,
invalidClass: "jsgrid-invalid",
containerClass: "jsgrid",
tableClass: "jsgrid-table",
gridHeaderClass: "jsgrid-grid-header",
gridBodyClass: "jsgrid-grid-body",
_init: function(config) {
$.extend(this, config);
this._initLoadStrategy();
this._initController();
this._initFields();
});
},
_attachWindowResizeCallback: function() {
$(window).on("resize", $.proxy(this._refreshSize, this));
},
_initLoadStrategy: function() {
this._loadStrategy = getOrApply(this.loadStrategy, this);
},
_initController: function() {
this._controller = $.extend({}, defaultController, getOrApply(this.controller, this));
},
renderTemplate: function(source, context, config) {
var args = [];
for(var key in config) {
args.push(config[key]);
}
args.unshift(source, context);
source = getOrApply.apply(null, args);
return (source === undefined || source === null) ? "" : source;
},
loadIndicator: function(config) {
return new jsGrid.LoadIndicator(config);
},
validation: function(config) {
return jsGrid.Validation && new jsGrid.Validation(config);
},
_initFields: function() {
var self = this;
self.fields = $.map(self.fields, function(field) {
if($.isPlainObject(field)) {
var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field;
field = new fieldConstructor(field);
}
field._grid = self;
return field;
});
},
_attachWindowLoadResize: function() {
$(window).on("load", $.proxy(this._refreshSize, this));
},
_attachWindowResizeCallback: function() {
if(this.updateOnResize) {
$(window).on("resize", $.proxy(this._refreshSize, this));
}
},
_detachWindowResizeCallback: function() {
$(window).off("resize", this._refreshSize);
},
option: function(key, value) {
var optionChangingEventArgs,
optionChangedEventArgs;
if(arguments.length === 1)
return this[key];
optionChangingEventArgs = {
option: key,
oldValue: this[key],
newValue: value
};
this._callEventHandler(this.onOptionChanging, optionChangingEventArgs);
this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue);
optionChangedEventArgs = {
option: optionChangingEventArgs.option,
value: optionChangingEventArgs.newValue
};
this._callEventHandler(this.onOptionChanged, optionChangedEventArgs);
},
fieldOption: function(field, key, value) {
field = this._normalizeField(field);
if(arguments.length === 2)
return field[key];
field[key] = value;
this._renderGrid();
},
_handleOptionChange: function(name, value) {
this[name] = value;
switch(name) {
case "width":
case "height":
this._refreshSize();
break;
case "rowClass":
case "rowRenderer":
case "rowClick":
case "rowDoubleClick":
case "noDataRowClass":
case "noDataContent":
case "selecting":
case "selectedRowClass":
case "oddRowClass":
case "evenRowClass":
this._refreshContent();
break;
case "pageButtonCount":
case "pagerFormat":
case "pagePrevText":
case "pageNextText":
case "pageFirstText":
case "pageLastText":
case "pageNavigatorNextText":
case "pageNavigatorPrevText":
case "pagerClass":
case "pagerNavButtonClass":
case "pageClass":
case "currentPageClass":
case "pagerRenderer":
this._refreshPager();
break;
case "fields":
this._initFields();
this.render();
this.refresh();
if(this.autoload) {
setTimeout($.proxy(this.loadData, this), 100);
}
},
this.refresh();
break;
case "loadStrategy":
case "pageLoading":
this._initLoadStrategy();
this.search();
break;
case "pageIndex":
this.openPage(value);
break;
case "pageSize":
this.refresh();
this.search();
break;
case "editRowRenderer":
case "editRowClass":
this.cancelEdit();
break;
case "updateOnResize":
this._detachWindowResizeCallback();
this._attachWindowResizeCallback();
break;
case "invalidNotify":
case "invalidMessage":
break;
default:
this.render();
break;
}
},
destroy: function() {
this._detachWindowResizeCallback();
this._clear();
this._container.removeData(JSGRID_DATA_KEY);
},
render: function() {
this._renderGrid();
return this.autoload ? this.loadData() : $.Deferred().resolve().promise();
},
_renderGrid: function() {
this._clear();
this._container.addClass(this.containerClass)
.css("position", "relative")
.append(this._createHeader())
.append(this._createBody());
this._pagerContainer = this._createPagerContainer();
this._loadIndicator = this._createLoadIndicator();
this._validation = this._createValidation();
this.refresh();
},
_createLoadIndicator: function() {
return getOrApply(this.loadIndicator, this, {
message: this.loadMessage,
shading: this.loadShading,
container: this._container
});
},
_createValidation: function() {
return getOrApply(this.validation, this);
},
_clear: function() {
this.cancelEdit();
clearTimeout(this._loadingTimer);
this._pagerContainer && this._pagerContainer.empty();
this._container.empty()
.css({ position: "", width: "", height: "" });
},
_createHeader: function() {
var $headerRow = this._headerRow = this._createHeaderRow(),
$filterRow = this._filterRow = this._createFilterRow(),
$insertRow = this._insertRow = this._createInsertRow();
var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass)
.append($headerRow)
.append($filterRow)
.append($insertRow);
var $header = this._header = $("<div>").addClass(this.gridHeaderClass)
.addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "")
.append($headerGrid);
return $header;
},
_createBody: function() {
var $content = this._content = $("<tbody>");
var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass)
.append($content);
var $body = this._body = $("<div>").addClass(this.gridBodyClass)
.append($bodyGrid)
.on("scroll", $.proxy(function(e) {
this._header.scrollLeft(e.target.scrollLeft);
}, this));
return $body;
},
_createPagerContainer: function() {
var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container);
return $(pagerContainer).addClass(this.pagerContainerClass);
},
_eachField: function(callBack) {
var self = this;
$.each(this.fields, function(index, field) {
if(field.visible) {
callBack.call(self, field, index);
}
});
},
_createHeaderRow: function() {
if($.isFunction(this.headerRowRenderer))
return $(this.renderTemplate(this.headerRowRenderer, this));
var $result = $("<tr>").addClass(this.headerRowClass);
this._eachField(function(field, index) {
var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass)
.append(this.renderTemplate(field.headerTemplate, field))
.appendTo($result);
if(this.sorting && field.sorting) {
$th.addClass(this.sortableClass)
.on("click", $.proxy(function() {
this.sort(index);
}, this));
}
});
return $result;
},
_prepareCell: function(cell, field, cssprop, cellClass) {
return $(cell).css("width", field.width)
.addClass(cellClass || this.cellClass)
.addClass((cssprop && field[cssprop]) || field.css)
.addClass(field.align ? ("jsgrid-align-" + field.align) : "");
},
_createFilterRow: function() {
if($.isFunction(this.filterRowRenderer))
return $(this.renderTemplate(this.filterRowRenderer, this));
var $result = $("<tr>").addClass(this.filterRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "filtercss")
.append(this.renderTemplate(field.filterTemplate, field))
.appendTo($result);
});
return $result;
},
_createInsertRow: function() {
if($.isFunction(this.insertRowRenderer))
return $(this.renderTemplate(this.insertRowRenderer, this));
var $result = $("<tr>").addClass(this.insertRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "insertcss")
.append(this.renderTemplate(field.insertTemplate, field))
.appendTo($result);
});
return $result;
},
_callEventHandler: function(handler, eventParams) {
handler.call(this, $.extend(eventParams, {
grid: this
}));
return eventParams;
},
reset: function() {
this._resetSorting();
this._resetPager();
return this._loadStrategy.reset();
},
_resetPager: function() {
this._firstDisplayingPage = 1;
this._setPage(1);
},
_resetSorting: function() {
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._clearSortingCss();
},
refresh: function() {
this._callEventHandler(this.onRefreshing);
this.cancelEdit();
this._refreshHeading();
this._refreshFiltering();
this._refreshInserting();
this._refreshContent();
this._refreshPager();
this._refreshSize();
this._callEventHandler(this.onRefreshed);
},
_refreshHeading: function() {
this._headerRow.toggle(this.heading);
},
_refreshFiltering: function() {
this._filterRow.toggle(this.filtering);
},
_refreshInserting: function() {
this._insertRow.toggle(this.inserting);
},
_refreshContent: function() {
var $content = this._content;
$content.empty();
if(!this.data.length) {
$content.append(this._createNoDataRow());
return this;
}
var indexFrom = this._loadStrategy.firstDisplayIndex();
var indexTo = this._loadStrategy.lastDisplayIndex();
for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) {
var item = this.data[itemIndex];
$content.append(this._createRow(item, itemIndex));
}
},
_createNoDataRow: function() {
var amountOfFields = 0;
this._eachField(function() {
amountOfFields++;
});
return $("<tr>").addClass(this.noDataRowClass)
.append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields)
.append(this.renderTemplate(this.noDataContent, this)));
},
_createRow: function(item, itemIndex) {
var $result;
if($.isFunction(this.rowRenderer)) {
$result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex });
} else {
$result = $("<tr>");
this._renderCells($result, item);
}
$result.addClass(this._getRowClasses(item, itemIndex))
.data(JSGRID_ROW_DATA_KEY, item)
.on("click", $.proxy(function(e) {
this.rowClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this))
.on("dblclick", $.proxy(function(e) {
this.rowDoubleClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this));
if(this.selecting) {
this._attachRowHover($result);
}
return $result;
},
_getRowClasses: function(item, itemIndex) {
var classes = [];
classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass);
classes.push(getOrApply(this.rowClass, this, item, itemIndex));
return classes.join(" ");
},
_attachRowHover: function($row) {
var selectedRowClass = this.selectedRowClass;
$row.hover(function() {
$(this).addClass(selectedRowClass);
},
function() {
$(this).removeClass(selectedRowClass);
}
);
},
_renderCells: function($row, item) {
this._eachField(function(field) {
$row.append(this._createCell(item, field));
});
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = this._getItemFieldValue(item, field);
var args = { value: fieldValue, item : item };
if($.isFunction(field.cellRenderer)) {
$result = this.renderTemplate(field.cellRenderer, field, args);
} else {
$result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args));
}
return this._prepareCell($result, field);
},
_getItemFieldValue: function(item, field) {
var props = field.name.split('.');
var result = item[props.shift()];
while(result && props.length) {
result = result[props.shift()];
}
return result;
},
_setItemFieldValue: function(item, field, value) {
var props = field.name.split('.');
var current = item;
var prop = props[0];
while(current && props.length) {
item = current;
prop = props.shift();
current = item[prop];
}
if(!current) {
while(props.length) {
item = item[prop] = {};
prop = props.shift();
}
}
item[prop] = value;
},
sort: function(field, order) {
if($.isPlainObject(field)) {
order = field.order;
field = field.field;
}
this._clearSortingCss();
this._setSortingParams(field, order);
this._setSortingCss();
return this._loadStrategy.sort();
},
_clearSortingCss: function() {
this._headerRow.find("th")
.removeClass(this.sortAscClass)
.removeClass(this.sortDescClass);
},
_setSortingParams: function(field, order) {
field = this._normalizeField(field);
order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC);
this._sortField = field;
this._sortOrder = order;
},
_normalizeField: function(field) {
if($.isNumeric(field)) {
return this.fields[field];
}
if(typeof field === "string") {
return $.grep(this.fields, function(f) {
return f.name === field;
})[0];
}
return field;
},
_reversedSortOrder: function(order) {
return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC);
},
_setSortingCss: function() {
var fieldIndex = this._visibleFieldIndex(this._sortField);
this._headerRow.find("th").eq(fieldIndex)
.addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass);
},
_visibleFieldIndex: function(field) {
return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; }));
},
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if(sortField) {
var self = this;
self.data.sort(function(item1, item2) {
var value1 = self._getItemFieldValue(item1, sortField);
var value2 = self._getItemFieldValue(item2, sortField);
return sortFactor * sortField.sortingFunc(value1, value2);
});
}
},
_sortFactor: function() {
return this._sortOrder === SORT_ORDER_ASC ? 1 : -1;
},
_itemsCount: function() {
return this._loadStrategy.itemsCount();
},
_pagesCount: function() {
var itemsCount = this._itemsCount(),
pageSize = this.pageSize;
return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0);
},
_refreshPager: function() {
var $pagerContainer = this._pagerContainer;
$pagerContainer.empty();
if(this.paging) {
$pagerContainer.append(this._createPager());
}
var showPager = this.paging && this._pagesCount() > 1;
$pagerContainer.toggle(showPager);
},
_createPager: function() {
var $result;
if($.isFunction(this.pagerRenderer)) {
$result = $(this.pagerRenderer({
pageIndex: this.pageIndex,
pageCount: this._pagesCount()
}));
} else {
$result = $("<div>").append(this._createPagerByFormat());
}
$result.addClass(this.pagerClass);
return $result;
},
_createPagerByFormat: function() {
var pageIndex = this.pageIndex,
pageCount = this._pagesCount(),
itemCount = this._itemsCount(),
pagerParts = this.pagerFormat.split(" ");
return $.map(pagerParts, $.proxy(function(pagerPart) {
var result = pagerPart;
if(pagerPart === PAGES_PLACEHOLDER) {
result = this._createPages();
} else if(pagerPart === FIRST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1);
} else if(pagerPart === PREV_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1);
} else if(pagerPart === NEXT_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount);
} else if(pagerPart === LAST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount);
} else if(pagerPart === PAGE_INDEX_PLACEHOLDER) {
result = pageIndex;
} else if(pagerPart === PAGE_COUNT_PLACEHOLDER) {
result = pageCount;
} else if(pagerPart === ITEM_COUNT_PLACEHOLDER) {
result = itemCount;
}
return $.isArray(result) ? result.concat([" "]) : [result, " "];
}, this));
},
_createPages: function() {
var pageCount = this._pagesCount(),
pageButtonCount = this.pageButtonCount,
firstDisplayingPage = this._firstDisplayingPage,
pages = [];
if(firstDisplayingPage > 1) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages));
}
for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) {
pages.push(pageNumber === this.pageIndex
? this._createPagerCurrentPage()
: this._createPagerPage(pageNumber));
}
if((firstDisplayingPage + pageButtonCount - 1) < pageCount) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages));
}
return pages;
},
_createPagerNavButton: function(text, pageIndex, isActive) {
return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass),
isActive ? function() { this.openPage(pageIndex); } : $.noop);
},
_createPagerPageNavButton: function(text, handler) {
return this._createPagerButton(text, this.pagerNavButtonClass, handler);
},
_createPagerPage: function(pageIndex) {
return this._createPagerButton(pageIndex, this.pageClass, function() {
this.openPage(pageIndex);
});
},
_createPagerButton: function(text, css, handler) {
var $link = $("<a>").attr("href", EMPTY_HREF)
.html(text)
.on("click", $.proxy(handler, this));
return $("<span>").addClass(css).append($link);
},
_createPagerCurrentPage: function() {
return $("<span>")
.addClass(this.pageClass)
.addClass(this.currentPageClass)
.text(this.pageIndex);
},
_refreshSize: function() {
this._refreshHeight();
this._refreshWidth();
},
_refreshWidth: function() {
var width = (this.width === "auto") ? this._getAutoWidth() : this.width;
this._container.width(width);
},
_getAutoWidth: function() {
var $headerGrid = this._headerGrid,
$header = this._header;
$headerGrid.width("auto");
var contentWidth = $headerGrid.outerWidth();
var borderWidth = $header.outerWidth() - $header.innerWidth();
$headerGrid.width("");
return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
var result;
return function() {
if(result === undefined) {
var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>");
var $ghostContent = $("<div style='height:100px;'></div>");
$ghostContainer.append($ghostContent).appendTo("body");
var width = $ghostContent.innerWidth();
$ghostContainer.css("overflow-y", "auto");
var widthExcludingScrollBar = $ghostContent.innerWidth();
$ghostContainer.remove();
result = width - widthExcludingScrollBar;
}
return result;
};
})(),
_refreshHeight: function() {
var container = this._container,
pagerContainer = this._pagerContainer,
height = this.height,
nonBodyHeight;
container.height(height);
if(height !== "auto") {
height = container.height();
nonBodyHeight = this._header.outerHeight(true);
if(pagerContainer.parents(container).length) {
nonBodyHeight += pagerContainer.outerHeight(true);
}
this._body.outerHeight(height - nonBodyHeight);
}
},
showPrevPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1;
this._refreshPager();
},
showNextPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount,
pageCount = this._pagesCount();
this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount)
? pageCount - pageButtonCount + 1
: firstDisplayingPage + pageButtonCount;
this._refreshPager();
},
openPage: function(pageIndex) {
if(pageIndex < 1 || pageIndex > this._pagesCount())
return;
this._setPage(pageIndex);
this._loadStrategy.openPage(pageIndex);
},
_setPage: function(pageIndex) {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this.pageIndex = pageIndex;
if(pageIndex < firstDisplayingPage) {
this._firstDisplayingPage = pageIndex;
}
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
this._callEventHandler(this.onPageChanged, {
pageIndex: pageIndex
});
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
if(isCanceled)
return $.Deferred().reject().promise();
this._showLoading();
var controller = this._controller;
if(!controller || !controller[method]) {
throw Error("controller has no method '" + method + "'");
}
return normalizePromise(controller[method](param))
.done($.proxy(doneCallback, this))
.fail($.proxy(this._errorHandler, this))
.always($.proxy(this._hideLoading, this));
},
_errorHandler: function() {
this._callEventHandler(this.onError, {
args: $.makeArray(arguments)
});
},
_showLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadingTimer = setTimeout($.proxy(function() {
this._loadIndicator.show();
}, this), this.loadIndicationDelay);
},
_hideLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadIndicator.hide();
},
search: function(filter) {
this._resetSorting();
this._resetPager();
return this.loadData(filter);
},
loadData: function(filter) {
filter = filter || (this.filtering ? this.getFilter() : {});
$.extend(filter, this._loadStrategy.loadParams(), this._sortingParams());
var args = this._callEventHandler(this.onDataLoading, {
filter: filter
});
return this._controllerCall("loadData", filter, args.cancel, function(loadedData) {
if(!loadedData)
return;
this._loadStrategy.finishLoad(loadedData);
this._callEventHandler(this.onDataLoaded, {
data: loadedData
});
});
},
exportData: function(exportOptions){
var options = exportOptions || {};
var type = options.type || "csv";
var result = "";
this._callEventHandler(this.onDataExporting);
switch(type){
case "csv":
result = this._dataToCsv(options);
break;
}
return result;
},
_dataToCsv: function(options){
var options = options || {};
var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true;
var subset = options.subset || "all";
var filter = options.filter || undefined;
var result = [];
if (includeHeaders){
var fieldsLength = this.fields.length;
var fieldNames = {};
for(var i=0;i<fieldsLength;i++){
var field = this.fields[i];
if ("includeInDataExport" in field){
if (field.includeInDataExport === true)
fieldNames[i] = field.title || field.name;
}
}
var headerLine = this._itemToCsv(fieldNames,{},options);
result.push(headerLine);
}
var exportStartIndex = 0;
var exportEndIndex = this.data.length;
switch(subset){
case "visible":
exportEndIndex = this._firstDisplayingPage * this.pageSize;
exportStartIndex = exportEndIndex - this.pageSize;
case "all":
default:
break;
}
for (var i = exportStartIndex; i < exportEndIndex; i++){
var item = this.data[i];
var itemLine = "";
var includeItem = true;
if (filter)
if (!filter(item))
includeItem = false;
if (includeItem){
itemLine = this._itemToCsv(item, this.fields, options);
result.push(itemLine);
}
}
return result.join("");
},
_itemToCsv: function(item, fields, options){
var options = options || {};
var delimiter = options.delimiter || "|";
var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true;
var newline = options.newline || "\r\n";
var transforms = options.transforms || {};
var fields = fields || {};
var getItem = this._getItemFieldValue;
var result = [];
Object.keys(item).forEach(function(key,index) {
var entry = "";
//Fields.length is greater than 0 when we are matching agaisnt fields
//Field.length will be 0 when exporting header rows
if (fields.length > 0){
var field = fields[index];
//Field may be excluded from data export
if ("includeInDataExport" in field){
if (field.includeInDataExport){
//Field may be a select, which requires additional logic
if (field.type === "select"){
var selectedItem = getItem(item, field);
var resultItem = $.grep(field.items, function(item, index) {
return item[field.valueField] === selectedItem;
})[0] || "";
entry = resultItem[field.textField];
}
else{
entry = getItem(item, field);
}
}
else{
return;
}
}
else{
entry = getItem(item, field);
}
if (transforms.hasOwnProperty(field.name)){
entry = transforms[field.name](entry);
}
}
else{
entry = item[key];
}
if (encapsulate){
entry = '"'+entry+'"';
}
result.push(entry);
});
return result.join(delimiter) + newline;
},
getFilter: function() {
var result = {};
this._eachField(function(field) {
if(field.filtering) {
this._setItemFieldValue(result, field, field.filterValue());
}
});
return result;
},
_sortingParams: function() {
if(this.sorting && this._sortField) {
return {
sortField: this._sortField.name,
sortOrder: this._sortOrder
};
}
return {};
},
getSorting: function() {
var sortingParams = this._sortingParams();
return {
field: sortingParams.sortField,
order: sortingParams.sortOrder
};
},
clearFilter: function() {
var $filterRow = this._createFilterRow();
this._filterRow.replaceWith($filterRow);
this._filterRow = $filterRow;
return this.search();
},
insertItem: function(item) {
var insertingItem = item || this._getValidatedInsertItem();
if(!insertingItem)
return $.Deferred().reject().promise();
var args = this._callEventHandler(this.onItemInserting, {
item: insertingItem
});
return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) {
insertedItem = insertedItem || insertingItem;
this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation);
this._callEventHandler(this.onItemInserted, {
item: insertedItem
});
});
},
_getValidatedInsertItem: function() {
var item = this._getInsertItem();
return this._validateItem(item, this._insertRow) ? item : null;
},
_getInsertItem: function() {
var result = {};
this._eachField(function(field) {
if(field.inserting) {
this._setItemFieldValue(result, field, field.insertValue());
}
});
return result;
},
_validateItem: function(item, $row) {
var validationErrors = [];
var args = {
item: item,
itemIndex: this._rowIndex($row),
row: $row
};
this._eachField(function(field) {
if(!field.validate ||
($row === this._insertRow && !field.inserting) ||
($row === this._getEditRow() && !field.editing))
return;
var fieldValue = this._getItemFieldValue(item, field);
var errors = this._validation.validate($.extend({
value: fieldValue,
rules: field.validate
}, args));
this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors);
if(!errors.length)
return;
validationErrors.push.apply(validationErrors,
$.map(errors, function(message) {
return { field: field, message: message };
}));
});
if(!validationErrors.length)
return true;
var invalidArgs = $.extend({
errors: validationErrors
}, args);
this._callEventHandler(this.onItemInvalid, invalidArgs);
this.invalidNotify(invalidArgs);
return false;
},
_setCellValidity: function($cell, errors) {
$cell
.toggleClass(this.invalidClass, !!errors.length)
.attr("title", errors.join("\n"));
},
clearInsert: function() {
var insertRow = this._createInsertRow();
this._insertRow.replaceWith(insertRow);
this._insertRow = insertRow;
this.refresh();
},
editItem: function(item) {
var $row = this.rowByItem(item);
if($row.length) {
this._editRow($row);
}
},
rowByItem: function(item) {
if(item.jquery || item.nodeType)
return $(item);
return this._content.find("tr").filter(function() {
return $.data(this, JSGRID_ROW_DATA_KEY) === item;
});
},
_editRow: function($row) {
if(!this.editing)
return;
var item = $row.data(JSGRID_ROW_DATA_KEY);
var args = this._callEventHandler(this.onItemEditing, {
row: $row,
item: item,
itemIndex: this._itemIndex(item)
});
if(args.cancel)
return;
if(this._editingRow) {
this.cancelEdit();
}
var $editRow = this._createEditRow(item);
this._editingRow = $row;
$row.hide();
$editRow.insertBefore($row);
$row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow);
},
_createEditRow: function(item) {
if($.isFunction(this.editRowRenderer)) {
return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) }));
}
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
var fieldValue = this._getItemFieldValue(item, field);
this._prepareCell("<td>", field, "editcss")
.append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item }))
.appendTo($result);
});
return $result;
},
updateItem: function(item, editedItem) {
if(arguments.length === 1) {
editedItem = item;
}
var $row = item ? this.rowByItem(item) : this._editingRow;
editedItem = editedItem || this._getValidatedEditedItem();
if(!editedItem)
return;
return this._updateRow($row, editedItem);
},
_getValidatedEditedItem: function() {
var item = this._getEditedItem();
return this._validateItem(item, this._getEditRow()) ? item : null;
},
_updateRow: function($updatingRow, editedItem) {
var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY),
updatingItemIndex = this._itemIndex(updatingItem),
updatedItem = $.extend(true, {}, updatingItem, editedItem);
var args = this._callEventHandler(this.onItemUpdating, {
row: $updatingRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: updatingItem
});
return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) {
var previousItem = $.extend(true, {}, updatingItem);
updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem);
var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex);
this._callEventHandler(this.onItemUpdated, {
row: $updatedRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: previousItem
});
});
},
_rowIndex: function(row) {
return this._content.children().index($(row));
},
_itemIndex: function(item) {
return $.inArray(item, this.data);
},
_finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) {
this.cancelEdit();
this.data[updatedItemIndex] = updatedItem;
var $updatedRow = this._createRow(updatedItem, updatedItemIndex);
$updatingRow.replaceWith($updatedRow);
return $updatedRow;
},
_getEditedItem: function() {
var result = {};
this._eachField(function(field) {
if(field.editing) {
this._setItemFieldValue(result, field, field.editValue());
}
});
return result;
},
cancelEdit: function() {
if(!this._editingRow)
return;
var $row = this._editingRow,
editingItem = $row.data(JSGRID_ROW_DATA_KEY),
editingItemIndex = this._itemIndex(editingItem);
this._callEventHandler(this.onItemEditCancelling, {
row: $row,
item: editingItem,
itemIndex: editingItemIndex
});
this._getEditRow().remove();
this._editingRow.show();
this._editingRow = null;
},
_getEditRow: function() {
return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY);
},
deleteItem: function(item) {
var $row = this.rowByItem(item);
if(!$row.length)
return;
if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY))))
return;
return this._deleteRow($row);
},
_deleteRow: function($row) {
var deletingItem = $row.data(JSGRID_ROW_DATA_KEY),
deletingItemIndex = this._itemIndex(deletingItem);
var args = this._callEventHandler(this.onItemDeleting, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
return this._controllerCall("deleteItem", deletingItem, args.cancel, function() {
this._loadStrategy.finishDelete(deletingItem, deletingItemIndex);
this._callEventHandler(this.onItemDeleted, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
});
}
};
$.fn.jsGrid = function(config) {
var args = $.makeArray(arguments),
methodArgs = args.slice(1),
result = this;
this.each(function() {
var $element = $(this),
instance = $element.data(JSGRID_DATA_KEY),
methodResult;
if(instance) {
if(typeof config === "string") {
methodResult = instance[config].apply(instance, methodArgs);
if(methodResult !== undefined && methodResult !== instance) {
result = methodResult;
return false;
}
} else {
instance._detachWindowResizeCallback();
instance._init(config);
instance.render();
}
} else {
new Grid($element, config);
}
});
return result;
};
var fields = {};
var setDefaults = function(config) {
var componentPrototype;
if($.isPlainObject(config)) {
componentPrototype = Grid.prototype;
} else {
componentPrototype = fields[config].prototype;
config = arguments[1] || {};
}
$.extend(componentPrototype, config);
};
var locales = {};
var locale = function(lang) {
var localeConfig = $.isPlainObject(lang) ? lang : locales[lang];
if(!localeConfig)
throw Error("unknown locale " + lang);
setLocale(jsGrid, localeConfig);
};
var setLocale = function(obj, localeConfig) {
$.each(localeConfig, function(field, value) {
if($.isPlainObject(value)) {
setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value);
return;
}
if(obj.hasOwnProperty(field)) {
obj[field] = value;
} else {
obj.prototype[field] = value;
}
});
};
window.jsGrid = {
Grid: Grid,
fields: fields,
setDefaults: setDefaults,
locales: locales,
locale: locale,
version: "@VERSION"
};
}(window, jQuery));
<MSG> Core: Resize grid on window.load
<DFF> @@ -150,7 +150,8 @@
this._initController();
this._initLoadIndicator();
this._initFields();
-
+ this._attachWindowLoadResize();
+
if(this.updateOnResize) {
this._attachWindowResizeCallback();
}
@@ -193,6 +194,10 @@
});
},
+ _attachWindowLoadResize: function() {
+ $(window).on("load", $.proxy(this._refreshSize, this));
+ },
+
_attachWindowResizeCallback: function() {
$(window).on("resize", $.proxy(this._refreshSize, this));
},
@@ -325,7 +330,7 @@
this.refresh();
if(this.autoload) {
- setTimeout($.proxy(this.loadData, this), 100);
+ this.loadData();
}
},
| 7 | Core: Resize grid on window.load | 2 | .js | core | mit | tabalinas/jsgrid |
10068379 | <NME> jsgrid.core.js
<BEF> (function(window, $, undefined) {
var JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID,
JSGRID_ROW_DATA_KEY = "JSGridItem",
JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow",
SORT_ORDER_ASC = "asc",
SORT_ORDER_DESC = "desc",
FIRST_PAGE_PLACEHOLDER = "{first}",
PAGES_PLACEHOLDER = "{pages}",
PREV_PAGE_PLACEHOLDER = "{prev}",
NEXT_PAGE_PLACEHOLDER = "{next}",
LAST_PAGE_PLACEHOLDER = "{last}",
PAGE_INDEX_PLACEHOLDER = "{pageIndex}",
PAGE_COUNT_PLACEHOLDER = "{pageCount}",
ITEM_COUNT_PLACEHOLDER = "{itemCount}",
EMPTY_HREF = "javascript:void(0);";
var getOrApply = function(value, context) {
if($.isFunction(value)) {
return value.apply(context, $.makeArray(arguments).slice(2));
}
return value;
};
var normalizePromise = function(promise) {
var d = $.Deferred();
if(promise && promise.then) {
promise.then(function() {
d.resolve.apply(d, arguments);
}, function() {
d.reject.apply(d, arguments);
});
} else {
d.resolve(promise);
}
return d.promise();
};
var defaultController = {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
};
function Grid(element, config) {
var $element = $(element);
$element.data(JSGRID_DATA_KEY, this);
this._container = $element;
this.data = [];
this.fields = [];
this._editingRow = null;
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._firstDisplayingPage = 1;
this._init(config);
this.render();
}
Grid.prototype = {
width: "auto",
height: "auto",
updateOnResize: true,
rowClass: $.noop,
rowRenderer: null,
rowClick: function(args) {
if(this.editing) {
this.editItem($(args.event.target).closest("tr"));
}
},
rowDoubleClick: $.noop,
noDataContent: "Not found",
noDataRowClass: "jsgrid-nodata-row",
heading: true,
headerRowRenderer: null,
headerRowClass: "jsgrid-header-row",
headerCellClass: "jsgrid-header-cell",
filtering: false,
filterRowRenderer: null,
filterRowClass: "jsgrid-filter-row",
inserting: false,
insertRowLocation: "bottom",
insertRowRenderer: null,
insertRowClass: "jsgrid-insert-row",
editing: false,
editRowRenderer: null,
editRowClass: "jsgrid-edit-row",
confirmDeleting: true,
deleteConfirm: "Are you sure?",
selecting: true,
selectedRowClass: "jsgrid-selected-row",
oddRowClass: "jsgrid-row",
evenRowClass: "jsgrid-alt-row",
cellClass: "jsgrid-cell",
sorting: false,
sortableClass: "jsgrid-header-sortable",
sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc",
sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc",
paging: false,
pagerContainer: null,
pageIndex: 1,
pageSize: 20,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
pagerContainerClass: "jsgrid-pager-container",
pagerClass: "jsgrid-pager",
pagerNavButtonClass: "jsgrid-pager-nav-button",
pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button",
pageClass: "jsgrid-pager-page",
currentPageClass: "jsgrid-pager-current-page",
customLoading: false,
pageLoading: false,
autoload: false,
controller: defaultController,
loadIndication: true,
loadIndicationDelay: 500,
loadMessage: "Please, wait...",
this._initController();
this._initLoadIndicator();
this._initFields();
if(this.updateOnResize) {
this._attachWindowResizeCallback();
}
window.alert([this.invalidMessage].concat(messages).join("\n"));
},
onInit: $.noop,
onRefreshing: $.noop,
onRefreshed: $.noop,
onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
onItemInserted: $.noop,
onItemEditing: $.noop,
onItemEditCancelling: $.noop,
onItemUpdating: $.noop,
onItemUpdated: $.noop,
onItemInvalid: $.noop,
onDataLoading: $.noop,
onDataLoaded: $.noop,
onDataExporting: $.noop,
onOptionChanging: $.noop,
onOptionChanged: $.noop,
onError: $.noop,
invalidClass: "jsgrid-invalid",
containerClass: "jsgrid",
tableClass: "jsgrid-table",
gridHeaderClass: "jsgrid-grid-header",
gridBodyClass: "jsgrid-grid-body",
_init: function(config) {
$.extend(this, config);
this._initLoadStrategy();
this._initController();
this._initFields();
});
},
_attachWindowResizeCallback: function() {
$(window).on("resize", $.proxy(this._refreshSize, this));
},
_initLoadStrategy: function() {
this._loadStrategy = getOrApply(this.loadStrategy, this);
},
_initController: function() {
this._controller = $.extend({}, defaultController, getOrApply(this.controller, this));
},
renderTemplate: function(source, context, config) {
var args = [];
for(var key in config) {
args.push(config[key]);
}
args.unshift(source, context);
source = getOrApply.apply(null, args);
return (source === undefined || source === null) ? "" : source;
},
loadIndicator: function(config) {
return new jsGrid.LoadIndicator(config);
},
validation: function(config) {
return jsGrid.Validation && new jsGrid.Validation(config);
},
_initFields: function() {
var self = this;
self.fields = $.map(self.fields, function(field) {
if($.isPlainObject(field)) {
var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field;
field = new fieldConstructor(field);
}
field._grid = self;
return field;
});
},
_attachWindowLoadResize: function() {
$(window).on("load", $.proxy(this._refreshSize, this));
},
_attachWindowResizeCallback: function() {
if(this.updateOnResize) {
$(window).on("resize", $.proxy(this._refreshSize, this));
}
},
_detachWindowResizeCallback: function() {
$(window).off("resize", this._refreshSize);
},
option: function(key, value) {
var optionChangingEventArgs,
optionChangedEventArgs;
if(arguments.length === 1)
return this[key];
optionChangingEventArgs = {
option: key,
oldValue: this[key],
newValue: value
};
this._callEventHandler(this.onOptionChanging, optionChangingEventArgs);
this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue);
optionChangedEventArgs = {
option: optionChangingEventArgs.option,
value: optionChangingEventArgs.newValue
};
this._callEventHandler(this.onOptionChanged, optionChangedEventArgs);
},
fieldOption: function(field, key, value) {
field = this._normalizeField(field);
if(arguments.length === 2)
return field[key];
field[key] = value;
this._renderGrid();
},
_handleOptionChange: function(name, value) {
this[name] = value;
switch(name) {
case "width":
case "height":
this._refreshSize();
break;
case "rowClass":
case "rowRenderer":
case "rowClick":
case "rowDoubleClick":
case "noDataRowClass":
case "noDataContent":
case "selecting":
case "selectedRowClass":
case "oddRowClass":
case "evenRowClass":
this._refreshContent();
break;
case "pageButtonCount":
case "pagerFormat":
case "pagePrevText":
case "pageNextText":
case "pageFirstText":
case "pageLastText":
case "pageNavigatorNextText":
case "pageNavigatorPrevText":
case "pagerClass":
case "pagerNavButtonClass":
case "pageClass":
case "currentPageClass":
case "pagerRenderer":
this._refreshPager();
break;
case "fields":
this._initFields();
this.render();
this.refresh();
if(this.autoload) {
setTimeout($.proxy(this.loadData, this), 100);
}
},
this.refresh();
break;
case "loadStrategy":
case "pageLoading":
this._initLoadStrategy();
this.search();
break;
case "pageIndex":
this.openPage(value);
break;
case "pageSize":
this.refresh();
this.search();
break;
case "editRowRenderer":
case "editRowClass":
this.cancelEdit();
break;
case "updateOnResize":
this._detachWindowResizeCallback();
this._attachWindowResizeCallback();
break;
case "invalidNotify":
case "invalidMessage":
break;
default:
this.render();
break;
}
},
destroy: function() {
this._detachWindowResizeCallback();
this._clear();
this._container.removeData(JSGRID_DATA_KEY);
},
render: function() {
this._renderGrid();
return this.autoload ? this.loadData() : $.Deferred().resolve().promise();
},
_renderGrid: function() {
this._clear();
this._container.addClass(this.containerClass)
.css("position", "relative")
.append(this._createHeader())
.append(this._createBody());
this._pagerContainer = this._createPagerContainer();
this._loadIndicator = this._createLoadIndicator();
this._validation = this._createValidation();
this.refresh();
},
_createLoadIndicator: function() {
return getOrApply(this.loadIndicator, this, {
message: this.loadMessage,
shading: this.loadShading,
container: this._container
});
},
_createValidation: function() {
return getOrApply(this.validation, this);
},
_clear: function() {
this.cancelEdit();
clearTimeout(this._loadingTimer);
this._pagerContainer && this._pagerContainer.empty();
this._container.empty()
.css({ position: "", width: "", height: "" });
},
_createHeader: function() {
var $headerRow = this._headerRow = this._createHeaderRow(),
$filterRow = this._filterRow = this._createFilterRow(),
$insertRow = this._insertRow = this._createInsertRow();
var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass)
.append($headerRow)
.append($filterRow)
.append($insertRow);
var $header = this._header = $("<div>").addClass(this.gridHeaderClass)
.addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "")
.append($headerGrid);
return $header;
},
_createBody: function() {
var $content = this._content = $("<tbody>");
var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass)
.append($content);
var $body = this._body = $("<div>").addClass(this.gridBodyClass)
.append($bodyGrid)
.on("scroll", $.proxy(function(e) {
this._header.scrollLeft(e.target.scrollLeft);
}, this));
return $body;
},
_createPagerContainer: function() {
var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container);
return $(pagerContainer).addClass(this.pagerContainerClass);
},
_eachField: function(callBack) {
var self = this;
$.each(this.fields, function(index, field) {
if(field.visible) {
callBack.call(self, field, index);
}
});
},
_createHeaderRow: function() {
if($.isFunction(this.headerRowRenderer))
return $(this.renderTemplate(this.headerRowRenderer, this));
var $result = $("<tr>").addClass(this.headerRowClass);
this._eachField(function(field, index) {
var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass)
.append(this.renderTemplate(field.headerTemplate, field))
.appendTo($result);
if(this.sorting && field.sorting) {
$th.addClass(this.sortableClass)
.on("click", $.proxy(function() {
this.sort(index);
}, this));
}
});
return $result;
},
_prepareCell: function(cell, field, cssprop, cellClass) {
return $(cell).css("width", field.width)
.addClass(cellClass || this.cellClass)
.addClass((cssprop && field[cssprop]) || field.css)
.addClass(field.align ? ("jsgrid-align-" + field.align) : "");
},
_createFilterRow: function() {
if($.isFunction(this.filterRowRenderer))
return $(this.renderTemplate(this.filterRowRenderer, this));
var $result = $("<tr>").addClass(this.filterRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "filtercss")
.append(this.renderTemplate(field.filterTemplate, field))
.appendTo($result);
});
return $result;
},
_createInsertRow: function() {
if($.isFunction(this.insertRowRenderer))
return $(this.renderTemplate(this.insertRowRenderer, this));
var $result = $("<tr>").addClass(this.insertRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "insertcss")
.append(this.renderTemplate(field.insertTemplate, field))
.appendTo($result);
});
return $result;
},
_callEventHandler: function(handler, eventParams) {
handler.call(this, $.extend(eventParams, {
grid: this
}));
return eventParams;
},
reset: function() {
this._resetSorting();
this._resetPager();
return this._loadStrategy.reset();
},
_resetPager: function() {
this._firstDisplayingPage = 1;
this._setPage(1);
},
_resetSorting: function() {
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._clearSortingCss();
},
refresh: function() {
this._callEventHandler(this.onRefreshing);
this.cancelEdit();
this._refreshHeading();
this._refreshFiltering();
this._refreshInserting();
this._refreshContent();
this._refreshPager();
this._refreshSize();
this._callEventHandler(this.onRefreshed);
},
_refreshHeading: function() {
this._headerRow.toggle(this.heading);
},
_refreshFiltering: function() {
this._filterRow.toggle(this.filtering);
},
_refreshInserting: function() {
this._insertRow.toggle(this.inserting);
},
_refreshContent: function() {
var $content = this._content;
$content.empty();
if(!this.data.length) {
$content.append(this._createNoDataRow());
return this;
}
var indexFrom = this._loadStrategy.firstDisplayIndex();
var indexTo = this._loadStrategy.lastDisplayIndex();
for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) {
var item = this.data[itemIndex];
$content.append(this._createRow(item, itemIndex));
}
},
_createNoDataRow: function() {
var amountOfFields = 0;
this._eachField(function() {
amountOfFields++;
});
return $("<tr>").addClass(this.noDataRowClass)
.append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields)
.append(this.renderTemplate(this.noDataContent, this)));
},
_createRow: function(item, itemIndex) {
var $result;
if($.isFunction(this.rowRenderer)) {
$result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex });
} else {
$result = $("<tr>");
this._renderCells($result, item);
}
$result.addClass(this._getRowClasses(item, itemIndex))
.data(JSGRID_ROW_DATA_KEY, item)
.on("click", $.proxy(function(e) {
this.rowClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this))
.on("dblclick", $.proxy(function(e) {
this.rowDoubleClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this));
if(this.selecting) {
this._attachRowHover($result);
}
return $result;
},
_getRowClasses: function(item, itemIndex) {
var classes = [];
classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass);
classes.push(getOrApply(this.rowClass, this, item, itemIndex));
return classes.join(" ");
},
_attachRowHover: function($row) {
var selectedRowClass = this.selectedRowClass;
$row.hover(function() {
$(this).addClass(selectedRowClass);
},
function() {
$(this).removeClass(selectedRowClass);
}
);
},
_renderCells: function($row, item) {
this._eachField(function(field) {
$row.append(this._createCell(item, field));
});
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = this._getItemFieldValue(item, field);
var args = { value: fieldValue, item : item };
if($.isFunction(field.cellRenderer)) {
$result = this.renderTemplate(field.cellRenderer, field, args);
} else {
$result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args));
}
return this._prepareCell($result, field);
},
_getItemFieldValue: function(item, field) {
var props = field.name.split('.');
var result = item[props.shift()];
while(result && props.length) {
result = result[props.shift()];
}
return result;
},
_setItemFieldValue: function(item, field, value) {
var props = field.name.split('.');
var current = item;
var prop = props[0];
while(current && props.length) {
item = current;
prop = props.shift();
current = item[prop];
}
if(!current) {
while(props.length) {
item = item[prop] = {};
prop = props.shift();
}
}
item[prop] = value;
},
sort: function(field, order) {
if($.isPlainObject(field)) {
order = field.order;
field = field.field;
}
this._clearSortingCss();
this._setSortingParams(field, order);
this._setSortingCss();
return this._loadStrategy.sort();
},
_clearSortingCss: function() {
this._headerRow.find("th")
.removeClass(this.sortAscClass)
.removeClass(this.sortDescClass);
},
_setSortingParams: function(field, order) {
field = this._normalizeField(field);
order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC);
this._sortField = field;
this._sortOrder = order;
},
_normalizeField: function(field) {
if($.isNumeric(field)) {
return this.fields[field];
}
if(typeof field === "string") {
return $.grep(this.fields, function(f) {
return f.name === field;
})[0];
}
return field;
},
_reversedSortOrder: function(order) {
return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC);
},
_setSortingCss: function() {
var fieldIndex = this._visibleFieldIndex(this._sortField);
this._headerRow.find("th").eq(fieldIndex)
.addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass);
},
_visibleFieldIndex: function(field) {
return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; }));
},
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if(sortField) {
var self = this;
self.data.sort(function(item1, item2) {
var value1 = self._getItemFieldValue(item1, sortField);
var value2 = self._getItemFieldValue(item2, sortField);
return sortFactor * sortField.sortingFunc(value1, value2);
});
}
},
_sortFactor: function() {
return this._sortOrder === SORT_ORDER_ASC ? 1 : -1;
},
_itemsCount: function() {
return this._loadStrategy.itemsCount();
},
_pagesCount: function() {
var itemsCount = this._itemsCount(),
pageSize = this.pageSize;
return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0);
},
_refreshPager: function() {
var $pagerContainer = this._pagerContainer;
$pagerContainer.empty();
if(this.paging) {
$pagerContainer.append(this._createPager());
}
var showPager = this.paging && this._pagesCount() > 1;
$pagerContainer.toggle(showPager);
},
_createPager: function() {
var $result;
if($.isFunction(this.pagerRenderer)) {
$result = $(this.pagerRenderer({
pageIndex: this.pageIndex,
pageCount: this._pagesCount()
}));
} else {
$result = $("<div>").append(this._createPagerByFormat());
}
$result.addClass(this.pagerClass);
return $result;
},
_createPagerByFormat: function() {
var pageIndex = this.pageIndex,
pageCount = this._pagesCount(),
itemCount = this._itemsCount(),
pagerParts = this.pagerFormat.split(" ");
return $.map(pagerParts, $.proxy(function(pagerPart) {
var result = pagerPart;
if(pagerPart === PAGES_PLACEHOLDER) {
result = this._createPages();
} else if(pagerPart === FIRST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1);
} else if(pagerPart === PREV_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1);
} else if(pagerPart === NEXT_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount);
} else if(pagerPart === LAST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount);
} else if(pagerPart === PAGE_INDEX_PLACEHOLDER) {
result = pageIndex;
} else if(pagerPart === PAGE_COUNT_PLACEHOLDER) {
result = pageCount;
} else if(pagerPart === ITEM_COUNT_PLACEHOLDER) {
result = itemCount;
}
return $.isArray(result) ? result.concat([" "]) : [result, " "];
}, this));
},
_createPages: function() {
var pageCount = this._pagesCount(),
pageButtonCount = this.pageButtonCount,
firstDisplayingPage = this._firstDisplayingPage,
pages = [];
if(firstDisplayingPage > 1) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages));
}
for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) {
pages.push(pageNumber === this.pageIndex
? this._createPagerCurrentPage()
: this._createPagerPage(pageNumber));
}
if((firstDisplayingPage + pageButtonCount - 1) < pageCount) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages));
}
return pages;
},
_createPagerNavButton: function(text, pageIndex, isActive) {
return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass),
isActive ? function() { this.openPage(pageIndex); } : $.noop);
},
_createPagerPageNavButton: function(text, handler) {
return this._createPagerButton(text, this.pagerNavButtonClass, handler);
},
_createPagerPage: function(pageIndex) {
return this._createPagerButton(pageIndex, this.pageClass, function() {
this.openPage(pageIndex);
});
},
_createPagerButton: function(text, css, handler) {
var $link = $("<a>").attr("href", EMPTY_HREF)
.html(text)
.on("click", $.proxy(handler, this));
return $("<span>").addClass(css).append($link);
},
_createPagerCurrentPage: function() {
return $("<span>")
.addClass(this.pageClass)
.addClass(this.currentPageClass)
.text(this.pageIndex);
},
_refreshSize: function() {
this._refreshHeight();
this._refreshWidth();
},
_refreshWidth: function() {
var width = (this.width === "auto") ? this._getAutoWidth() : this.width;
this._container.width(width);
},
_getAutoWidth: function() {
var $headerGrid = this._headerGrid,
$header = this._header;
$headerGrid.width("auto");
var contentWidth = $headerGrid.outerWidth();
var borderWidth = $header.outerWidth() - $header.innerWidth();
$headerGrid.width("");
return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
var result;
return function() {
if(result === undefined) {
var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>");
var $ghostContent = $("<div style='height:100px;'></div>");
$ghostContainer.append($ghostContent).appendTo("body");
var width = $ghostContent.innerWidth();
$ghostContainer.css("overflow-y", "auto");
var widthExcludingScrollBar = $ghostContent.innerWidth();
$ghostContainer.remove();
result = width - widthExcludingScrollBar;
}
return result;
};
})(),
_refreshHeight: function() {
var container = this._container,
pagerContainer = this._pagerContainer,
height = this.height,
nonBodyHeight;
container.height(height);
if(height !== "auto") {
height = container.height();
nonBodyHeight = this._header.outerHeight(true);
if(pagerContainer.parents(container).length) {
nonBodyHeight += pagerContainer.outerHeight(true);
}
this._body.outerHeight(height - nonBodyHeight);
}
},
showPrevPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1;
this._refreshPager();
},
showNextPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount,
pageCount = this._pagesCount();
this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount)
? pageCount - pageButtonCount + 1
: firstDisplayingPage + pageButtonCount;
this._refreshPager();
},
openPage: function(pageIndex) {
if(pageIndex < 1 || pageIndex > this._pagesCount())
return;
this._setPage(pageIndex);
this._loadStrategy.openPage(pageIndex);
},
_setPage: function(pageIndex) {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this.pageIndex = pageIndex;
if(pageIndex < firstDisplayingPage) {
this._firstDisplayingPage = pageIndex;
}
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
this._callEventHandler(this.onPageChanged, {
pageIndex: pageIndex
});
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
if(isCanceled)
return $.Deferred().reject().promise();
this._showLoading();
var controller = this._controller;
if(!controller || !controller[method]) {
throw Error("controller has no method '" + method + "'");
}
return normalizePromise(controller[method](param))
.done($.proxy(doneCallback, this))
.fail($.proxy(this._errorHandler, this))
.always($.proxy(this._hideLoading, this));
},
_errorHandler: function() {
this._callEventHandler(this.onError, {
args: $.makeArray(arguments)
});
},
_showLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadingTimer = setTimeout($.proxy(function() {
this._loadIndicator.show();
}, this), this.loadIndicationDelay);
},
_hideLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadIndicator.hide();
},
search: function(filter) {
this._resetSorting();
this._resetPager();
return this.loadData(filter);
},
loadData: function(filter) {
filter = filter || (this.filtering ? this.getFilter() : {});
$.extend(filter, this._loadStrategy.loadParams(), this._sortingParams());
var args = this._callEventHandler(this.onDataLoading, {
filter: filter
});
return this._controllerCall("loadData", filter, args.cancel, function(loadedData) {
if(!loadedData)
return;
this._loadStrategy.finishLoad(loadedData);
this._callEventHandler(this.onDataLoaded, {
data: loadedData
});
});
},
exportData: function(exportOptions){
var options = exportOptions || {};
var type = options.type || "csv";
var result = "";
this._callEventHandler(this.onDataExporting);
switch(type){
case "csv":
result = this._dataToCsv(options);
break;
}
return result;
},
_dataToCsv: function(options){
var options = options || {};
var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true;
var subset = options.subset || "all";
var filter = options.filter || undefined;
var result = [];
if (includeHeaders){
var fieldsLength = this.fields.length;
var fieldNames = {};
for(var i=0;i<fieldsLength;i++){
var field = this.fields[i];
if ("includeInDataExport" in field){
if (field.includeInDataExport === true)
fieldNames[i] = field.title || field.name;
}
}
var headerLine = this._itemToCsv(fieldNames,{},options);
result.push(headerLine);
}
var exportStartIndex = 0;
var exportEndIndex = this.data.length;
switch(subset){
case "visible":
exportEndIndex = this._firstDisplayingPage * this.pageSize;
exportStartIndex = exportEndIndex - this.pageSize;
case "all":
default:
break;
}
for (var i = exportStartIndex; i < exportEndIndex; i++){
var item = this.data[i];
var itemLine = "";
var includeItem = true;
if (filter)
if (!filter(item))
includeItem = false;
if (includeItem){
itemLine = this._itemToCsv(item, this.fields, options);
result.push(itemLine);
}
}
return result.join("");
},
_itemToCsv: function(item, fields, options){
var options = options || {};
var delimiter = options.delimiter || "|";
var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true;
var newline = options.newline || "\r\n";
var transforms = options.transforms || {};
var fields = fields || {};
var getItem = this._getItemFieldValue;
var result = [];
Object.keys(item).forEach(function(key,index) {
var entry = "";
//Fields.length is greater than 0 when we are matching agaisnt fields
//Field.length will be 0 when exporting header rows
if (fields.length > 0){
var field = fields[index];
//Field may be excluded from data export
if ("includeInDataExport" in field){
if (field.includeInDataExport){
//Field may be a select, which requires additional logic
if (field.type === "select"){
var selectedItem = getItem(item, field);
var resultItem = $.grep(field.items, function(item, index) {
return item[field.valueField] === selectedItem;
})[0] || "";
entry = resultItem[field.textField];
}
else{
entry = getItem(item, field);
}
}
else{
return;
}
}
else{
entry = getItem(item, field);
}
if (transforms.hasOwnProperty(field.name)){
entry = transforms[field.name](entry);
}
}
else{
entry = item[key];
}
if (encapsulate){
entry = '"'+entry+'"';
}
result.push(entry);
});
return result.join(delimiter) + newline;
},
getFilter: function() {
var result = {};
this._eachField(function(field) {
if(field.filtering) {
this._setItemFieldValue(result, field, field.filterValue());
}
});
return result;
},
_sortingParams: function() {
if(this.sorting && this._sortField) {
return {
sortField: this._sortField.name,
sortOrder: this._sortOrder
};
}
return {};
},
getSorting: function() {
var sortingParams = this._sortingParams();
return {
field: sortingParams.sortField,
order: sortingParams.sortOrder
};
},
clearFilter: function() {
var $filterRow = this._createFilterRow();
this._filterRow.replaceWith($filterRow);
this._filterRow = $filterRow;
return this.search();
},
insertItem: function(item) {
var insertingItem = item || this._getValidatedInsertItem();
if(!insertingItem)
return $.Deferred().reject().promise();
var args = this._callEventHandler(this.onItemInserting, {
item: insertingItem
});
return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) {
insertedItem = insertedItem || insertingItem;
this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation);
this._callEventHandler(this.onItemInserted, {
item: insertedItem
});
});
},
_getValidatedInsertItem: function() {
var item = this._getInsertItem();
return this._validateItem(item, this._insertRow) ? item : null;
},
_getInsertItem: function() {
var result = {};
this._eachField(function(field) {
if(field.inserting) {
this._setItemFieldValue(result, field, field.insertValue());
}
});
return result;
},
_validateItem: function(item, $row) {
var validationErrors = [];
var args = {
item: item,
itemIndex: this._rowIndex($row),
row: $row
};
this._eachField(function(field) {
if(!field.validate ||
($row === this._insertRow && !field.inserting) ||
($row === this._getEditRow() && !field.editing))
return;
var fieldValue = this._getItemFieldValue(item, field);
var errors = this._validation.validate($.extend({
value: fieldValue,
rules: field.validate
}, args));
this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors);
if(!errors.length)
return;
validationErrors.push.apply(validationErrors,
$.map(errors, function(message) {
return { field: field, message: message };
}));
});
if(!validationErrors.length)
return true;
var invalidArgs = $.extend({
errors: validationErrors
}, args);
this._callEventHandler(this.onItemInvalid, invalidArgs);
this.invalidNotify(invalidArgs);
return false;
},
_setCellValidity: function($cell, errors) {
$cell
.toggleClass(this.invalidClass, !!errors.length)
.attr("title", errors.join("\n"));
},
clearInsert: function() {
var insertRow = this._createInsertRow();
this._insertRow.replaceWith(insertRow);
this._insertRow = insertRow;
this.refresh();
},
editItem: function(item) {
var $row = this.rowByItem(item);
if($row.length) {
this._editRow($row);
}
},
rowByItem: function(item) {
if(item.jquery || item.nodeType)
return $(item);
return this._content.find("tr").filter(function() {
return $.data(this, JSGRID_ROW_DATA_KEY) === item;
});
},
_editRow: function($row) {
if(!this.editing)
return;
var item = $row.data(JSGRID_ROW_DATA_KEY);
var args = this._callEventHandler(this.onItemEditing, {
row: $row,
item: item,
itemIndex: this._itemIndex(item)
});
if(args.cancel)
return;
if(this._editingRow) {
this.cancelEdit();
}
var $editRow = this._createEditRow(item);
this._editingRow = $row;
$row.hide();
$editRow.insertBefore($row);
$row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow);
},
_createEditRow: function(item) {
if($.isFunction(this.editRowRenderer)) {
return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) }));
}
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
var fieldValue = this._getItemFieldValue(item, field);
this._prepareCell("<td>", field, "editcss")
.append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item }))
.appendTo($result);
});
return $result;
},
updateItem: function(item, editedItem) {
if(arguments.length === 1) {
editedItem = item;
}
var $row = item ? this.rowByItem(item) : this._editingRow;
editedItem = editedItem || this._getValidatedEditedItem();
if(!editedItem)
return;
return this._updateRow($row, editedItem);
},
_getValidatedEditedItem: function() {
var item = this._getEditedItem();
return this._validateItem(item, this._getEditRow()) ? item : null;
},
_updateRow: function($updatingRow, editedItem) {
var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY),
updatingItemIndex = this._itemIndex(updatingItem),
updatedItem = $.extend(true, {}, updatingItem, editedItem);
var args = this._callEventHandler(this.onItemUpdating, {
row: $updatingRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: updatingItem
});
return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) {
var previousItem = $.extend(true, {}, updatingItem);
updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem);
var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex);
this._callEventHandler(this.onItemUpdated, {
row: $updatedRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: previousItem
});
});
},
_rowIndex: function(row) {
return this._content.children().index($(row));
},
_itemIndex: function(item) {
return $.inArray(item, this.data);
},
_finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) {
this.cancelEdit();
this.data[updatedItemIndex] = updatedItem;
var $updatedRow = this._createRow(updatedItem, updatedItemIndex);
$updatingRow.replaceWith($updatedRow);
return $updatedRow;
},
_getEditedItem: function() {
var result = {};
this._eachField(function(field) {
if(field.editing) {
this._setItemFieldValue(result, field, field.editValue());
}
});
return result;
},
cancelEdit: function() {
if(!this._editingRow)
return;
var $row = this._editingRow,
editingItem = $row.data(JSGRID_ROW_DATA_KEY),
editingItemIndex = this._itemIndex(editingItem);
this._callEventHandler(this.onItemEditCancelling, {
row: $row,
item: editingItem,
itemIndex: editingItemIndex
});
this._getEditRow().remove();
this._editingRow.show();
this._editingRow = null;
},
_getEditRow: function() {
return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY);
},
deleteItem: function(item) {
var $row = this.rowByItem(item);
if(!$row.length)
return;
if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY))))
return;
return this._deleteRow($row);
},
_deleteRow: function($row) {
var deletingItem = $row.data(JSGRID_ROW_DATA_KEY),
deletingItemIndex = this._itemIndex(deletingItem);
var args = this._callEventHandler(this.onItemDeleting, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
return this._controllerCall("deleteItem", deletingItem, args.cancel, function() {
this._loadStrategy.finishDelete(deletingItem, deletingItemIndex);
this._callEventHandler(this.onItemDeleted, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
});
}
};
$.fn.jsGrid = function(config) {
var args = $.makeArray(arguments),
methodArgs = args.slice(1),
result = this;
this.each(function() {
var $element = $(this),
instance = $element.data(JSGRID_DATA_KEY),
methodResult;
if(instance) {
if(typeof config === "string") {
methodResult = instance[config].apply(instance, methodArgs);
if(methodResult !== undefined && methodResult !== instance) {
result = methodResult;
return false;
}
} else {
instance._detachWindowResizeCallback();
instance._init(config);
instance.render();
}
} else {
new Grid($element, config);
}
});
return result;
};
var fields = {};
var setDefaults = function(config) {
var componentPrototype;
if($.isPlainObject(config)) {
componentPrototype = Grid.prototype;
} else {
componentPrototype = fields[config].prototype;
config = arguments[1] || {};
}
$.extend(componentPrototype, config);
};
var locales = {};
var locale = function(lang) {
var localeConfig = $.isPlainObject(lang) ? lang : locales[lang];
if(!localeConfig)
throw Error("unknown locale " + lang);
setLocale(jsGrid, localeConfig);
};
var setLocale = function(obj, localeConfig) {
$.each(localeConfig, function(field, value) {
if($.isPlainObject(value)) {
setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value);
return;
}
if(obj.hasOwnProperty(field)) {
obj[field] = value;
} else {
obj.prototype[field] = value;
}
});
};
window.jsGrid = {
Grid: Grid,
fields: fields,
setDefaults: setDefaults,
locales: locales,
locale: locale,
version: "@VERSION"
};
}(window, jQuery));
<MSG> Core: Resize grid on window.load
<DFF> @@ -150,7 +150,8 @@
this._initController();
this._initLoadIndicator();
this._initFields();
-
+ this._attachWindowLoadResize();
+
if(this.updateOnResize) {
this._attachWindowResizeCallback();
}
@@ -193,6 +194,10 @@
});
},
+ _attachWindowLoadResize: function() {
+ $(window).on("load", $.proxy(this._refreshSize, this));
+ },
+
_attachWindowResizeCallback: function() {
$(window).on("resize", $.proxy(this._refreshSize, this));
},
@@ -325,7 +330,7 @@
this.refresh();
if(this.autoload) {
- setTimeout($.proxy(this.loadData, this), 100);
+ this.loadData();
}
},
| 7 | Core: Resize grid on window.load | 2 | .js | core | mit | tabalinas/jsgrid |
10068380 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068381 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068382 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068383 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068384 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068385 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068386 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068387 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068388 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068389 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068390 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068391 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068392 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068393 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068394 | <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.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </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, 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;
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure(DispatcherPriority.Normal);
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
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();
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
// TODO: put redraw into background so that other input events can be handled before the redraw.
// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
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>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
Redraw(DispatcherPriority.Normal);
}
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure(redrawPriority);
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure(redrawPriority);
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
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)
// 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(redrawPriority);
}
}
}
}
}
if (changedSomethingBeforeOrInLine)
{
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(DispatcherPriority.Normal);
}
/// <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, DispatcherPriority priority)
{
InvalidateMeasure(priority);
}
/// <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, DispatcherPriority redrawPriority)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length, redrawPriority);
}
}
/// <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();
}
#endregion
#region InvalidateMeasure(DispatcherPriority)
private Task _invalidateMeasureOperation;
private void InvalidateMeasure(DispatcherPriority priority)
{
if (priority >= DispatcherPriority.Render)
{
_invalidateMeasureOperation = null;
InvalidateMeasure();
}
else
{
if (_invalidateMeasureOperation == null)
{
_invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidateMeasureOperation = null;
base.InvalidateMeasure();
},
priority
);
}
}
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// 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>
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure(DispatcherPriority.Normal);
// force immediate re-measure
InvalidateVisual();
}
/// 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();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// 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;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
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>();
VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView));
var elementGeneratorsArray = _elementGenerators.ToArray();
var lineTransformersArray = _lineTransformers.ToArray();
var nextLine = firstLineInView;
double maxWidth = 0;
var yPos = -_clippedPixelsOnTop;
while (yPos < availableSize.Height && nextLine != null)
{
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?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
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>
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure(DispatcherPriority.Normal);
if (_visibleVisualLines != null)
{
{
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));
inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
Debug.WriteLine(distance);
}
offset += span.TextSourceLength;
}
pos = new Point(pos.X, pos.Y + textLine.Height);
}
}
}
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)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
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)
{
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);
}
}
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;
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
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);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
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;
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
#endregion
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>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
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)
continue;
return element;
}
}
return null;
}
#endregion
#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);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
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);
}
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
{
InvalidateVisual();
TextLayer.InvalidateVisual();
InvalidateMeasure(DispatcherPriority.Normal);
}
if (isY)
{
InvalidateMeasure(DispatcherPriority.Normal);
}
}
}
}
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();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual
Remove the deferred InvalidateMeasure
<DFF> @@ -149,7 +149,7 @@ namespace AvaloniaEdit.Rendering
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
@@ -163,11 +163,7 @@ namespace AvaloniaEdit.Rendering
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
- // TODO: put redraw into background so that other input events can be handled before the redraw.
- // Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
- // the caret position change forces an immediate redraw, and the text input then forces a background redraw.
- // When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
- Redraw(e.Offset, e.RemovalLength, DispatcherPriority.Normal);
+ Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
@@ -611,37 +607,29 @@ namespace AvaloniaEdit.Rendering
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
- {
- Redraw(DispatcherPriority.Normal);
- }
-
- /// <summary>
- /// Causes the text editor to regenerate all visual lines.
- /// </summary>
- public void Redraw(DispatcherPriority redrawPriority)
{
VerifyAccess();
ClearVisualLines();
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
- public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority)
+ public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
- InvalidateMeasure(redrawPriority);
+ InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
- public void Redraw(int offset, int length, DispatcherPriority redrawPriority)
+ public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
@@ -666,7 +654,7 @@ namespace AvaloniaEdit.Rendering
// 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(redrawPriority);
+ InvalidateMeasure();
}
}
@@ -679,30 +667,18 @@ namespace AvaloniaEdit.Rendering
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(DispatcherPriority.Normal);
- }
-
- /// <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, DispatcherPriority priority)
- {
- InvalidateMeasure(priority);
+ 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, DispatcherPriority redrawPriority)
+ public void Redraw(ISegment segment)
{
if (segment != null)
{
- Redraw(segment.Offset, segment.Length, redrawPriority);
+ Redraw(segment.Offset, segment.Length);
}
}
@@ -737,34 +713,6 @@ namespace AvaloniaEdit.Rendering
}
#endregion
- #region InvalidateMeasure(DispatcherPriority)
-
- private Task _invalidateMeasureOperation;
-
- private void InvalidateMeasure(DispatcherPriority priority)
- {
- if (priority >= DispatcherPriority.Render)
- {
- _invalidateMeasureOperation = null;
- InvalidateMeasure();
- }
- else
- {
- if (_invalidateMeasureOperation == null)
- {
- _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync(
- delegate
- {
- _invalidateMeasureOperation = null;
- base.InvalidateMeasure();
- },
- priority
- );
- }
- }
- }
- #endregion
-
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
@@ -880,7 +828,7 @@ namespace AvaloniaEdit.Rendering
if (!VisualLinesValid)
{
// increase priority for re-measure
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
@@ -1211,7 +1159,7 @@ namespace AvaloniaEdit.Rendering
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
if (_visibleVisualLines != null)
{
@@ -1594,7 +1542,7 @@ namespace AvaloniaEdit.Rendering
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
#endregion
@@ -2081,7 +2029,7 @@ namespace AvaloniaEdit.Rendering
{
_canHorizontallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2095,7 +2043,7 @@ namespace AvaloniaEdit.Rendering
{
_canVerticallyScroll = value;
ClearVisualLines();
- InvalidateMeasure(DispatcherPriority.Normal);
+ InvalidateMeasure();
}
}
}
@@ -2124,13 +2072,9 @@ namespace AvaloniaEdit.Rendering
{
InvalidateVisual();
TextLayer.InvalidateVisual();
- InvalidateMeasure(DispatcherPriority.Normal);
}
- if (isY)
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ InvalidateMeasure();
}
}
}
| 16 | Merge pull request #249 from AvaloniaUI/remove-deferred-invalidate-visual | 72 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068395 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068396 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068397 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068398 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068399 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068400 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068401 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068402 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068403 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068404 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068405 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068406 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068407 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068408 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068409 | <NME> AvaloniaEdit.Tests.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" />
<ProjectReference Include="..\..\src\AvaloniaEdit\AvaloniaEdit.csproj" />
</ItemGroup>
</Project>
<MSG> Start porting to Avalonia's TextFormatter
<DFF> @@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageReference Include="Avalonia" Version="0.10.999-cibuild0019056-beta" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="NUnit" Version="3.11.0" />
| 1 | Start porting to Avalonia's TextFormatter | 1 | .csproj | Tests/AvaloniaEdit | mit | AvaloniaUI/AvaloniaEdit |
10068410 | <NME> Gruntfile.js
<BEF> module.exports = function(grunt) {
"use strict"
var banner =
"/*\n" +
" * jsGrid v<%= pkg.version %> (<%= pkg.homepage %>)\n" +
" * (c) <%= grunt.template.today('yyyy') %> <%= pkg.author %>\n" +
" * Licensed under <%= pkg.license.type %> (<%= pkg.license.url %>)\n" +
" */\n";
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
copy: {
imgs: {
expand: true,
cwd: "css/",
src: "*.png",
dest: "dist/"
},
i18n: {
expand: true,
cwd: "src/i18n/",
src: "*.js",
dest: "dist/i18n/",
rename: function(dest, src) {
return dest + "jsgrid-" + src;
}
}
},
concat: {
options: {
banner: banner + "\n",
separator: "\n"
},
js: {
src: [
"src/jsgrid.core.js",
"src/jsgrid.load-indicator.js",
"src/jsgrid.load-strategies.js",
"src/jsgrid.sort-strategies.js",
"src/jsgrid.field.js",
"src/fields/jsgrid.field.text.js",
"src/fields/jsgrid.field.number.js",
"src/fields/jsgrid.field.textarea.js",
"src/fields/jsgrid.field.select.js",
"src/fields/jsgrid.field.checkbox.js",
"src/fields/jsgrid.field.control.js"
],
dest: "dist/<%= pkg.name %>.js"
},
css: {
src: "css/jsgrid.css",
dest: "dist/<%= pkg.name %>.css"
},
theme: {
src: "css/theme.css",
dest: "dist/<%= pkg.name %>-theme.css"
}
},
"string-replace": {
version: {
files: [{
src: "<%= concat.js.dest %>",
dest: "<%= concat.js.dest %>"
}],
options: {
replacements: [{
pattern: /"@VERSION"/g,
replacement: "'<%= pkg.version %>'"
}]
}
}
},
imageEmbed: {
options: {
deleteAfterEncoding : true
},
theme: {
src: "<%= concat.theme.dest %>",
dest: "<%= concat.theme.dest %>"
}
},
uglify: {
options : {
banner: banner + "\n"
},
js: {
src: "<%= concat.js.dest %>",
dest: "dist/<%= pkg.name %>.min.js"
}
},
cssmin: {
options : {
banner: banner
},
css: {
src: "<%= concat.css.dest %>",
dest: "dist/<%= pkg.name %>.min.css"
},
theme: {
src: "<%= concat.theme.dest %>",
dest: "dist/<%= pkg.name %>-theme.min.css"
}
},
qunit: {
files: ["tests/index.html"]
}
});
grunt.loadNpmTasks("grunt-contrib-copy");
grunt.loadNpmTasks("grunt-contrib-concat");
grunt.loadNpmTasks("grunt-contrib-uglify");
grunt.loadNpmTasks("grunt-image-embed");
grunt.loadNpmTasks("grunt-contrib-cssmin");
grunt.loadNpmTasks("grunt-contrib-qunit");
grunt.loadNpmTasks('grunt-string-replace');
grunt.registerTask("default", ["copy", "concat", "string-replace", "imageEmbed", "uglify", "cssmin"]);
grunt.registerTask("test", "qunit");
};
<MSG> Config: Include validation into main script
Fixes: #207
<DFF> @@ -40,6 +40,7 @@
"src/jsgrid.load-indicator.js",
"src/jsgrid.load-strategies.js",
"src/jsgrid.sort-strategies.js",
+ "src/jsgrid.validation.js",
"src/jsgrid.field.js",
"src/fields/jsgrid.field.text.js",
"src/fields/jsgrid.field.number.js",
| 1 | Config: Include validation into main script | 0 | .js | js | mit | tabalinas/jsgrid |
10068411 | <NME> Gruntfile.js
<BEF> module.exports = function(grunt) {
"use strict"
var banner =
"/*\n" +
" * jsGrid v<%= pkg.version %> (<%= pkg.homepage %>)\n" +
" * (c) <%= grunt.template.today('yyyy') %> <%= pkg.author %>\n" +
" * Licensed under <%= pkg.license.type %> (<%= pkg.license.url %>)\n" +
" */\n";
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
copy: {
imgs: {
expand: true,
cwd: "css/",
src: "*.png",
dest: "dist/"
},
i18n: {
expand: true,
cwd: "src/i18n/",
src: "*.js",
dest: "dist/i18n/",
rename: function(dest, src) {
return dest + "jsgrid-" + src;
}
}
},
concat: {
options: {
banner: banner + "\n",
separator: "\n"
},
js: {
src: [
"src/jsgrid.core.js",
"src/jsgrid.load-indicator.js",
"src/jsgrid.load-strategies.js",
"src/jsgrid.sort-strategies.js",
"src/jsgrid.field.js",
"src/fields/jsgrid.field.text.js",
"src/fields/jsgrid.field.number.js",
"src/fields/jsgrid.field.textarea.js",
"src/fields/jsgrid.field.select.js",
"src/fields/jsgrid.field.checkbox.js",
"src/fields/jsgrid.field.control.js"
],
dest: "dist/<%= pkg.name %>.js"
},
css: {
src: "css/jsgrid.css",
dest: "dist/<%= pkg.name %>.css"
},
theme: {
src: "css/theme.css",
dest: "dist/<%= pkg.name %>-theme.css"
}
},
"string-replace": {
version: {
files: [{
src: "<%= concat.js.dest %>",
dest: "<%= concat.js.dest %>"
}],
options: {
replacements: [{
pattern: /"@VERSION"/g,
replacement: "'<%= pkg.version %>'"
}]
}
}
},
imageEmbed: {
options: {
deleteAfterEncoding : true
},
theme: {
src: "<%= concat.theme.dest %>",
dest: "<%= concat.theme.dest %>"
}
},
uglify: {
options : {
banner: banner + "\n"
},
js: {
src: "<%= concat.js.dest %>",
dest: "dist/<%= pkg.name %>.min.js"
}
},
cssmin: {
options : {
banner: banner
},
css: {
src: "<%= concat.css.dest %>",
dest: "dist/<%= pkg.name %>.min.css"
},
theme: {
src: "<%= concat.theme.dest %>",
dest: "dist/<%= pkg.name %>-theme.min.css"
}
},
qunit: {
files: ["tests/index.html"]
}
});
grunt.loadNpmTasks("grunt-contrib-copy");
grunt.loadNpmTasks("grunt-contrib-concat");
grunt.loadNpmTasks("grunt-contrib-uglify");
grunt.loadNpmTasks("grunt-image-embed");
grunt.loadNpmTasks("grunt-contrib-cssmin");
grunt.loadNpmTasks("grunt-contrib-qunit");
grunt.loadNpmTasks('grunt-string-replace');
grunt.registerTask("default", ["copy", "concat", "string-replace", "imageEmbed", "uglify", "cssmin"]);
grunt.registerTask("test", "qunit");
};
<MSG> Config: Include validation into main script
Fixes: #207
<DFF> @@ -40,6 +40,7 @@
"src/jsgrid.load-indicator.js",
"src/jsgrid.load-strategies.js",
"src/jsgrid.sort-strategies.js",
+ "src/jsgrid.validation.js",
"src/jsgrid.field.js",
"src/fields/jsgrid.field.text.js",
"src/fields/jsgrid.field.number.js",
| 1 | Config: Include validation into main script | 0 | .js | js | mit | tabalinas/jsgrid |
10068412 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068413 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068414 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068415 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068416 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068417 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068418 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068419 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068420 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068421 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068422 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068423 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068424 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068425 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068426 | <NME> ExtensionMethods.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.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.VisualTree;
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
//}
//public static Point TransformFromDevice(this Point point, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return new Point(point.X * matrix.M11, point.Y * matrix.M22);
//}
#endregion
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> correct whitespace.
<DFF> @@ -178,7 +178,7 @@ namespace AvaloniaEdit.Utils
#region System.Drawing <-> Avalonia conversions
public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this System.Drawing.Point p)
| 1 | correct whitespace. | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10068427 | <NME> events.js
<BEF>
/**
* Module Dependencies
*/
var events = require('evt');
/**
* Local vars
*/
var listenerMap = {};
/**
* Registers a event listener.
*
* @param {String} name
* @param {String} module
* @param {Function} cb
* @return {View}
*/
exports.on = function(name, module, cb) {
var l;
// cb can be passed as
// the second or third argument
if (typeof module !== 'string') {
cb = module;
module = null;
}
// if a module is provided
// pass in a special callback
// function that checks the
// module
if (module) {
if (!listenerMap[name]) listenerMap[name] = [];
l = listenerMap[name].push({
orig: cb,
cb: function() {
if (this.event.target.module() === module) {
cb.apply(this, arguments);
}
}
});
events.prototype.on.call(this, name, listenerMap[name][l-1].cb);
} else {
events.prototype.on.call(this, name, cb);
}
return this;
};
/**
* Unregisters a event listener.
*
* @param {String} name
* @param {String} module
* @param {Function} cb
* @return {View}
*/
exports.off = function(name, module, cb) {
// cb can be passed as
// the second or third argument
if (typeof module !== 'string') {
cb = module;
module = null;
}
if (module) {
listenerMap[name] = listenerMap[name].filter(function(map, index) {
// If a callback provided, keep it
// in the listener map if it doesn't match
if (cb && map.orig !== cb) {
return true;
// Otherwise remove it from the listener
// map and unbind the event listener
} else {
events.prototype.off.call(this, name, map.cb);
return false;
}
}, this);
}
if (!module) {
events.prototype.off.call(this, name, cb);
}
return this;
};
/**
* Fires an event on a view.
*
* @param {String} name
* @return {View}
*/
exports.fire = function(name) {
var _event = this.event;
var event = {
target: this,
propagate: true,
stopPropagation: function(){ this.propagate = false; }
};
propagate(this, arguments, event);
// COMPLEX:
// If an earlier event object was
// cached, restore the the event
// back onto the view. If there
// wasn't an earlier event, make
// sure the `event` key has been
// deleted off the view.
if (_event) this.event = _event;
else delete this.event;
// Allow chaining
return this;
};
function propagate(view, args, event) {
if (!view || !event.propagate) return;
view.event = event;
events.prototype.fire.apply(view, args);
propagate(view.parent, args, event);
}
exports.fireStatic = events.prototype.fire;
<MSG> Remove unused variable
<DFF> @@ -69,7 +69,7 @@ exports.off = function(name, module, cb) {
}
if (module) {
- listenerMap[name] = listenerMap[name].filter(function(map, index) {
+ listenerMap[name] = listenerMap[name].filter(function(map) {
// If a callback provided, keep it
// in the listener map if it doesn't match
| 1 | Remove unused variable | 1 | .js | js | mit | ftlabs/fruitmachine |
10068428 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068429 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068430 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068431 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068432 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068433 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068434 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068435 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068436 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068437 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068438 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068439 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068440 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068441 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068442 | <NME> TextEditorModel.cs
<BEF> using System;
using System.Collections.Generic;
using Avalonia.Threading;
using AvaloniaEdit.Rendering;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public class TextEditorModel : AbstractLineList, IDisposable
{
private readonly TextDocument _document;
private readonly TextView _textView;
private DocumentSnapshot _documentSnapshot;
private Action<Exception> _exceptionHandler;
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
private List<LineRange> _lineRanges = new List<LineRange>();
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
_textView = textView;
_document = document;
_exceptionHandler = exceptionHandler;
_documentSnapshot = new DocumentSnapshot(_document);
for (int i = 0; i < _document.LineCount; i++)
AddLine(i);
_document.Changing += DocumentOnChanging;
_document.Changed += DocumentOnChanged;
_document.UpdateFinished += DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
}
public override void Dispose()
{
_document.Changing -= DocumentOnChanging;
_document.Changed -= DocumentOnChanged;
_document.UpdateFinished -= DocumentOnUpdateFinished;
_textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged;
}
public override void UpdateLine(int lineIndex) { }
public void InvalidateViewPortLines()
{
if (!_textView.VisualLinesValid ||
{
lock (_lock)
{
_lineRanges.Clear();
foreach (var line in _document.Lines)
{
_lineRanges.Add(new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
});
}
}
}
public override int GetLineLength(int lineIndex)
{
return _documentSnapshot.GetLineLength(lineIndex);
}
private void TextView_ScrollOffsetChanged(object sender, EventArgs e)
{
try
{
TokenizeViewPort();
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanging(object sender, DocumentChangeEventArgs e)
{
try
{
if (e.RemovalLength > 0)
{
var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1;
for (int i = endLine; i > startLine; i--)
{
RemoveLine(i);
}
_documentSnapshot.RemoveLines(startLine, endLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void DocumentOnChanged(object sender, DocumentChangeEventArgs e)
{
try
{
int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1;
int endLine = startLine;
if (e.InsertionLength > 0)
{
endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1;
for (int i = startLine; i < endLine; i++)
{
AddLine(i);
}
}
_documentSnapshot.Update(e);
if (startLine == 0)
{
SetInvalidRange(startLine, endLine);
return;
}
// some grammars (JSON, csharp, ...)
// need to invalidate the previous line too
SetInvalidRange(startLine - 1, endLine);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void SetInvalidRange(int startLine, int endLine)
{
if (!_document.IsInUpdate)
{
InvalidateLineRange(startLine, endLine);
return;
}
// we're in a document change, store the max invalid range
if (_invalidRange == null)
{
_invalidRange = new InvalidLineRange(startLine, endLine);
return;
}
_invalidRange.SetInvalidRange(startLine, endLine);
}
void DocumentOnUpdateFinished(object sender, EventArgs e)
{
if (_invalidRange == null)
return;
try
{
InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine);
}
finally
{
_invalidRange = null;
}
}
private void TokenizeViewPort()
{
Dispatcher.UIThread.InvokeAsync(() =>
lock(_lock)
{
var line = _document.Lines[lineIndex];
_lineRanges[lineIndex] = new LineRange()
{
Offset = line.Offset,
Length = line.TotalLength
};
}
}
}, DispatcherPriority.MinValue);
}
internal class InvalidLineRange
{
internal int StartLine { get; private set; }
internal int EndLine { get; private set; }
internal InvalidLineRange(int startLine, int endLine)
{
StartLine = startLine;
EndLine = endLine;
}
internal void SetInvalidRange(int startLine, int endLine)
{
if (startLine < StartLine)
StartLine = startLine;
if (endLine > EndLine)
EndLine = endLine;
}
}
}
}
<MSG> Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure
Performing allocations and de-allocations in high frequency causes GC pressure and hurt performance. Using ArrayPool we get rid of them.
<DFF> @@ -1,4 +1,5 @@
using System;
+using System.Buffers;
using System.Collections.Generic;
using Avalonia.Threading;
@@ -17,7 +18,7 @@ namespace AvaloniaEdit.TextMate
private readonly TextView _textView;
private int _lineCount;
private ITextSource _textSource;
- private List<LineRange> _lineRanges = new List<LineRange>();
+ private LineRange[] _lineRanges;
private Action<Exception> _exceptionHandler;
public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler)
@@ -52,14 +53,17 @@ namespace AvaloniaEdit.TextMate
{
lock (_lock)
{
- _lineRanges.Clear();
- foreach (var line in _document.Lines)
+ int count = _document.Lines.Count;
+
+ if (_lineRanges != null)
+ ArrayPool<LineRange>.Shared.Return(_lineRanges);
+
+ _lineRanges = ArrayPool<LineRange>.Shared.Rent(count);
+ for (int i = 0; i < count; i++)
{
- _lineRanges.Add(new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- });
+ var line = _document.Lines[i];
+ _lineRanges[i].Offset = line.Offset;
+ _lineRanges[i].Length = line.TotalLength;
}
}
}
@@ -178,11 +182,8 @@ namespace AvaloniaEdit.TextMate
lock(_lock)
{
var line = _document.Lines[lineIndex];
- _lineRanges[lineIndex] = new LineRange()
- {
- Offset = line.Offset,
- Length = line.TotalLength
- };
+ _lineRanges[lineIndex].Offset = line.Offset;
+ _lineRanges[lineIndex].Length = line.TotalLength;
}
}
| 14 | Store the line ranges in arrays rented from the ArrayPool to avoid GC pressure | 13 | .cs | TextMate/TextEditorModel | mit | AvaloniaUI/AvaloniaEdit |
10068443 | <NME> helpers.js
<BEF>
describe('fruitmachine#helpers()', function() {
var testHelper;
beforeEach(function() {
testHelper = function(view) {
view.on('before initialize', testHelper.beforeInitialize);
view.on('initialize', testHelper.initialize);
view.on('setup', testHelper.setup);
view.on('teardown', testHelper.teardown);
view.on('destroy', testHelper.destroy);
};
testHelper.beforeInitialize = jest.fn();
testHelper.initialize = jest.fn();
testHelper.setup = jest.fn();
testHelper.teardown = jest.fn();
testHelper.destroy = jest.fn();
});
test("helpers `before initialize` and `initialize` should have been called, in that order", function() {
var view = fruitmachine({
module: 'apple',
helpers: [testHelper]
});
expect(testHelper.initialize).toHaveBeenCalled();
expect(testHelper.beforeInitialize).toHaveBeenCalled();
expect(testHelper.initialize.mock.invocationCallOrder).toEqual([2]);
expect(testHelper.beforeInitialize.mock.invocationCallOrder).toEqual([1]);
expect(testHelper.setup).toHaveBeenCalledTimes(0);
expect(testHelper.teardown).toHaveBeenCalledTimes(0);
expect(testHelper.destroy).toHaveBeenCalledTimes(0);
});
test("helper `setup` should have been called", function() {
var view = fruitmachine({
module: 'apple',
helpers: [testHelper]
});
expect(testHelper.setup).toHaveBeenCalledTimes(0);
assert.called(this.spys.destroy);
},
tearDown: function() {
this.view.destroy();
.teardown()
.destroy();
expect(testHelper.teardown).toHaveBeenCalled();
expect(testHelper.destroy).toHaveBeenCalled();
});
});
<MSG> Added test for helpers as functions
<DFF> @@ -43,6 +43,19 @@ buster.testCase('FruitMachine#helpers()', {
assert.called(this.spys.destroy);
},
+ "Should be able to pass functions into `helpers` array if helper hasn't been defined": function() {
+ var spy = this.spy();
+ var view = new helpers.Apple({
+ helpers: [
+ function(view) {
+ view.on('initialize', spy);
+ }
+ ]
+ });
+
+ assert.called(spy);
+ },
+
tearDown: function() {
this.view.destroy();
| 13 | Added test for helpers as functions | 0 | .js | js | mit | ftlabs/fruitmachine |
10068444 | <NME> module.render.js
<BEF>
describe('View#render()', function() {
var viewToTest;
beforeEach(function() {
viewToTest = helpers.createView();
});
test("The master view should have an element post render.", function() {
viewToTest.render();
expect(viewToTest.el).toBeDefined();
});
test("before render and render events should be fired", function() {
var beforeRenderSpy = jest.fn();
var renderSpy = jest.fn();
viewToTest.on('before render', beforeRenderSpy);
viewToTest.on('render', renderSpy);
viewToTest.render();
expect(beforeRenderSpy.mock.invocationCallOrder[0]).toBeLessThan(renderSpy.mock.invocationCallOrder[0]);
});
test("Data should be present in the generated markup.", function() {
var text = 'some orange text';
var orange = new Orange({
model: {
text: text
}
});
orange
.render()
.inject(sandbox);
expect(orange.el.innerHTML).toEqual(text);
});
test("Should be able to use Backbone models", function() {
var orange = new Orange({
model: {
text: 'orange text'
}
});
orange.render();
expect(orange.el.innerHTML).toEqual('orange text');
});
test("Child html should be present in the parent.", function() {
var layout = new Layout();
var apple = new Apple();
layout
.add(apple, 1)
.render();
firstChild = layout.el.firstElementChild;
expect(firstChild.classList.contains('apple')).toBe(true);
});
test("Should be of the tag specified", function() {
var apple = new Apple({ tag: 'ul' });
apple.render();
expect('UL').toEqual(apple.el.tagName);
});
test("Should have classes on the element", function() {
var apple = new Apple({
classes: ['foo', 'bar']
});
apple.render();
expect('apple foo bar').toEqual(apple.el.className);
});
test("Should have an id attribute with the value of `fmid`", function() {
var apple = new Apple({
classes: ['foo', 'bar']
});
apple.render();
expect(apple._fmid).toEqual(apple.el.id);
});
test("Should have populated all child module.el properties", function() {
var layout = new Layout({
children: {
1: {
module: 'apple',
children: {
1: {
module: 'apple',
children: {
1: {
module: 'apple'
}
assert(apple3.el);
},
"tearDown": helpers.destroyView
});
children: {
1: { module: 'apple' }
}
});
layout.render();
layout.el.setAttribute('data-test', 'should-not-be-blown-away');
layout.module('apple').el.setAttribute('data-test', 'should-be-blown-away');
layout.render();
// The DOM node of the FM module that render is called on should be recycled
expect(layout.el.getAttribute('data-test')).toEqual('should-not-be-blown-away');
// The DOM node of a child FM module to the one render is called on should not be recycled
expect(layout.module('apple').el.getAttribute('data-test')).not.toEqual('should-be-blown-away');
});
test("Classes should be updated on render", function() {
var layout = new Layout();
layout.render();
layout.classes = ['should-be-added'];
layout.render();
expect(layout.el.className).toEqual('layout should-be-added');
});
test("Classes added through the DOM should persist between renders", function() {
var layout = new Layout();
layout.render();
layout.el.classList.add('should-persist');
layout.render();
expect(layout.el.className).toEqual('layout should-persist');
});
test("Should fire unmount on children when rerendering", function() {
var appleSpy = jest.fn();
var orangeSpy = jest.fn();
var pearSpy = jest.fn();
viewToTest.module('apple').on('unmount', appleSpy);
viewToTest.module('orange').on('unmount', orangeSpy);
viewToTest.module('pear').on('unmount', pearSpy);
viewToTest.render();
expect(appleSpy).not.toHaveBeenCalled();
expect(orangeSpy).not.toHaveBeenCalled();
expect(pearSpy).not.toHaveBeenCalled();
viewToTest.render();
expect(appleSpy).toHaveBeenCalled();
expect(orangeSpy).toHaveBeenCalled();
expect(pearSpy).toHaveBeenCalled();
});
afterEach(function() {
helpers.destroyView();
viewToTest = null;
});
});
<MSG> Add test to check that the outer layer of a FM family tree is recycled between renders
<DFF> @@ -100,5 +100,20 @@ buster.testCase('View#render()', {
assert(apple3.el);
},
+ "The outer DOM node should be recycled between #renders": function() {
+ var layout = new Layout({
+ children: {
+ 1: { module: 'apple' }
+ }
+ });
+ layout.render();
+ layout.el.classList.add('should-not-be-blown-away');
+ layout.module('apple').el.classList.add('should-be-blown-away');
+
+ layout.render();
+ assert(layout.el.classList.contains('should-not-be-blown-away'), 'the DOM node of the FM module that render is called on should be recycled');
+ refute(layout.module('apple').el.classList.contains('should-be-blown-away'), 'the DOM node of a child FM module to the one render is called on should not be recycled');
+ },
+
"tearDown": helpers.destroyView
});
| 15 | Add test to check that the outer layer of a FM family tree is recycled between renders | 0 | .js | render | mit | ftlabs/fruitmachine |
10068445 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle"
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> overide fontsize and fontfamily.
<DFF> @@ -31,7 +31,7 @@
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
- VerticalAlignment="Top">
+ VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle"
| 1 | overide fontsize and fontfamily. | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10068446 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle"
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> overide fontsize and fontfamily.
<DFF> @@ -31,7 +31,7 @@
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
- VerticalAlignment="Top">
+ VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle"
| 1 | overide fontsize and fontfamily. | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10068447 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle"
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> overide fontsize and fontfamily.
<DFF> @@ -31,7 +31,7 @@
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
- VerticalAlignment="Top">
+ VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle"
| 1 | overide fontsize and fontfamily. | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10068448 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle"
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> overide fontsize and fontfamily.
<DFF> @@ -31,7 +31,7 @@
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
- VerticalAlignment="Top">
+ VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle"
| 1 | overide fontsize and fontfamily. | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10068449 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle"
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> overide fontsize and fontfamily.
<DFF> @@ -31,7 +31,7 @@
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
- VerticalAlignment="Top">
+ VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<ToggleButton Classes="ExpanderToggle"
| 1 | overide fontsize and fontfamily. | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.