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
10061150
<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; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); 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> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); 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> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); 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> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; 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); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } 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; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// 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); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge branch 'feature/ilogical-scrolling' into features/build-scripts <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Merge branch 'feature/ilogical-scrolling' into features/build-scripts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061151
<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; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); 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> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); 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> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); 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> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; 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); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } 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; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// 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); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge branch 'feature/ilogical-scrolling' into features/build-scripts <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Merge branch 'feature/ilogical-scrolling' into features/build-scripts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061152
<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; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); 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> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); 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> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); 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> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; 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); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } 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; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// 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); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge branch 'feature/ilogical-scrolling' into features/build-scripts <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Merge branch 'feature/ilogical-scrolling' into features/build-scripts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061153
<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; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); 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> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); 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> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); 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> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; 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); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } 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; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// 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); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge branch 'feature/ilogical-scrolling' into features/build-scripts <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Merge branch 'feature/ilogical-scrolling' into features/build-scripts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061154
<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; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); 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> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); 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> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); 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> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; 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); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } 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; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// 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); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge branch 'feature/ilogical-scrolling' into features/build-scripts <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Merge branch 'feature/ilogical-scrolling' into features/build-scripts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061155
<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; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); 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> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); 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> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); 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> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; 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); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } 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; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// 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); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge branch 'feature/ilogical-scrolling' into features/build-scripts <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Merge branch 'feature/ilogical-scrolling' into features/build-scripts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061156
<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; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); 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> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); 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> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); 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> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; 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); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } 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; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// 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); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge branch 'feature/ilogical-scrolling' into features/build-scripts <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Merge branch 'feature/ilogical-scrolling' into features/build-scripts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061157
<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; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); 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> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); 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> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); 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> //} } private bool _canVerticallyScroll; private bool _canHorizontallyScroll; 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); /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); } 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; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// 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); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge branch 'feature/ilogical-scrolling' into features/build-scripts <DFF> @@ -1387,7 +1387,7 @@ namespace AvaloniaEdit.Rendering //} } - private bool _canVerticallyScroll; + private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; @@ -1411,7 +1411,7 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - private void SetScrollOffset(Vector vector) + internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y);
2
Merge branch 'feature/ilogical-scrolling' into features/build-scripts
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061158
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061159
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061160
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061161
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061162
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061163
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061164
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061165
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061166
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061167
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061168
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061169
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061170
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061171
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061172
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.12" /> </ItemGroup> </Project> <MSG> Update to TextMateSharp v1.0.13 This version of TextMateSharp fixes a leak in TMModel threads not being properly disposed. <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.12" /> + <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project>
1
Update to TextMateSharp v1.0.13
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10061173
<NME> loadjs.min.js <BEF> !function(n,t){function e(n,t){n=n.push?n:[n];var e,o,r,i,u=[],c=n.length,f=c;for(e=function(n,e){e.length&&u.push(n),f-=1,0===f&&t(u)};c--;)o=n[c],r=l[o],r?e(o,r):(i=d[o]=d[o]||[],i.push(e))}function o(n,t){if(n){var e=d[n];if(l[n]=t,e)for(;e.length;)e[0](n,t),e.splice(0,1)}}function r(n,e){var o=t.createElement("script");o.style="text/javascript",o.async=!0,o.src=n,o.onload=o.onerror=function(t){o.parentNode.removeChild(o),o=null,e(n,t.type)},c.appendChild(o)}function i(n,t){n=n.push?n:[n];var e,o=n.length,i=o,u=[];for(e=function(n,e){"error"===e&&u.push(n),i-=1,0===i&&t(u)};o--;)r(n[o],e)}function u(t,e,r,u){var c,l,d;if(e&&!e.call&&(c=e),l=c?r:e,d=c?u:r,c){if(c in a)throw new Error("LoadJS: Bundle already defined");a[c]=!0}n.setTimeout(function(){i(t,function(n){n.length?(d||f)(n):(l||f)(),o(c,n)})},0)}var c=t.head,f=function(){},a={},l={},d={};u.ready=function(n,t,o){return e(n,function(n){n.length?(o||f)(n):(t||f)()}),u},u.done=function(n){o(n,[])},n.loadjs=u}(window,document); <MSG> removed unnecessary script attributes from code, bumped version number <DFF> @@ -1,1 +1,1 @@ -!function(n,t){function e(n,t){n=n.push?n:[n];var e,o,r,i,u=[],c=n.length,f=c;for(e=function(n,e){e.length&&u.push(n),f-=1,0===f&&t(u)};c--;)o=n[c],r=l[o],r?e(o,r):(i=d[o]=d[o]||[],i.push(e))}function o(n,t){if(n){var e=d[n];if(l[n]=t,e)for(;e.length;)e[0](n,t),e.splice(0,1)}}function r(n,e){var o=t.createElement("script");o.style="text/javascript",o.async=!0,o.src=n,o.onload=o.onerror=function(t){o.parentNode.removeChild(o),o=null,e(n,t.type)},c.appendChild(o)}function i(n,t){n=n.push?n:[n];var e,o=n.length,i=o,u=[];for(e=function(n,e){"error"===e&&u.push(n),i-=1,0===i&&t(u)};o--;)r(n[o],e)}function u(t,e,r,u){var c,l,d;if(e&&!e.call&&(c=e),l=c?r:e,d=c?u:r,c){if(c in a)throw new Error("LoadJS: Bundle already defined");a[c]=!0}n.setTimeout(function(){i(t,function(n){n.length?(d||f)(n):(l||f)(),o(c,n)})},0)}var c=t.head,f=function(){},a={},l={},d={};u.ready=function(n,t,o){return e(n,function(n){n.length?(o||f)(n):(t||f)()}),u},u.done=function(n){o(n,[])},n.loadjs=u}(window,document); \ No newline at end of file +!function(n,o){function e(n,o){n=n.push?n:[n];var e,t,r,i,u=[],f=n.length,c=f;for(e=function(n,e){e.length&&u.push(n),c-=1,0===c&&o(u)};f--;)t=n[f],r=a[t],r?e(t,r):(i=d[t]=d[t]||[],i.push(e))}function t(n,o){if(n){var e=d[n];if(a[n]=o,e)for(;e.length;)e[0](n,o),e.splice(0,1)}}function r(n,e){var t=o.createElement("script");t.src=n,t.onload=t.onerror=function(o){t.parentNode.removeChild(t),t=null,e(n,o.type)},f.appendChild(t)}function i(n,o){n=n.push?n:[n];var e,t=n.length,i=t,u=[];for(e=function(n,e){"error"===e&&u.push(n),i-=1,0===i&&o(u)};t--;)r(n[t],e)}function u(o,e,r,u){var f,a,d;if(e&&!e.call&&(f=e),a=f?r:e,d=f?u:r,f){if(f in l)throw new Error("LoadJS: Bundle already defined");l[f]=!0}n.setTimeout(function(){i(o,function(n){n.length?(d||c)(n):(a||c)(),t(f,n)})},0)}var f=o.head,c=function(){},l={},a={},d={};u.ready=function(n,o,t){return e(n,function(n){n.length?(t||c)(n):(o||c)()}),u},u.done=function(n){t(n,[])},n.loadjs=u}(window,document); \ No newline at end of file
1
removed unnecessary script attributes from code, bumped version number
1
.js
min
mit
muicss/loadjs
10061174
<NME> loadjs.min.js <BEF> !function(n,t){function e(n,t){n=n.push?n:[n];var e,o,r,i,u=[],c=n.length,f=c;for(e=function(n,e){e.length&&u.push(n),f-=1,0===f&&t(u)};c--;)o=n[c],r=l[o],r?e(o,r):(i=d[o]=d[o]||[],i.push(e))}function o(n,t){if(n){var e=d[n];if(l[n]=t,e)for(;e.length;)e[0](n,t),e.splice(0,1)}}function r(n,e){var o=t.createElement("script");o.style="text/javascript",o.async=!0,o.src=n,o.onload=o.onerror=function(t){o.parentNode.removeChild(o),o=null,e(n,t.type)},c.appendChild(o)}function i(n,t){n=n.push?n:[n];var e,o=n.length,i=o,u=[];for(e=function(n,e){"error"===e&&u.push(n),i-=1,0===i&&t(u)};o--;)r(n[o],e)}function u(t,e,r,u){var c,l,d;if(e&&!e.call&&(c=e),l=c?r:e,d=c?u:r,c){if(c in a)throw new Error("LoadJS: Bundle already defined");a[c]=!0}n.setTimeout(function(){i(t,function(n){n.length?(d||f)(n):(l||f)(),o(c,n)})},0)}var c=t.head,f=function(){},a={},l={},d={};u.ready=function(n,t,o){return e(n,function(n){n.length?(o||f)(n):(t||f)()}),u},u.done=function(n){o(n,[])},n.loadjs=u}(window,document); <MSG> removed unnecessary script attributes from code, bumped version number <DFF> @@ -1,1 +1,1 @@ -!function(n,t){function e(n,t){n=n.push?n:[n];var e,o,r,i,u=[],c=n.length,f=c;for(e=function(n,e){e.length&&u.push(n),f-=1,0===f&&t(u)};c--;)o=n[c],r=l[o],r?e(o,r):(i=d[o]=d[o]||[],i.push(e))}function o(n,t){if(n){var e=d[n];if(l[n]=t,e)for(;e.length;)e[0](n,t),e.splice(0,1)}}function r(n,e){var o=t.createElement("script");o.style="text/javascript",o.async=!0,o.src=n,o.onload=o.onerror=function(t){o.parentNode.removeChild(o),o=null,e(n,t.type)},c.appendChild(o)}function i(n,t){n=n.push?n:[n];var e,o=n.length,i=o,u=[];for(e=function(n,e){"error"===e&&u.push(n),i-=1,0===i&&t(u)};o--;)r(n[o],e)}function u(t,e,r,u){var c,l,d;if(e&&!e.call&&(c=e),l=c?r:e,d=c?u:r,c){if(c in a)throw new Error("LoadJS: Bundle already defined");a[c]=!0}n.setTimeout(function(){i(t,function(n){n.length?(d||f)(n):(l||f)(),o(c,n)})},0)}var c=t.head,f=function(){},a={},l={},d={};u.ready=function(n,t,o){return e(n,function(n){n.length?(o||f)(n):(t||f)()}),u},u.done=function(n){o(n,[])},n.loadjs=u}(window,document); \ No newline at end of file +!function(n,o){function e(n,o){n=n.push?n:[n];var e,t,r,i,u=[],f=n.length,c=f;for(e=function(n,e){e.length&&u.push(n),c-=1,0===c&&o(u)};f--;)t=n[f],r=a[t],r?e(t,r):(i=d[t]=d[t]||[],i.push(e))}function t(n,o){if(n){var e=d[n];if(a[n]=o,e)for(;e.length;)e[0](n,o),e.splice(0,1)}}function r(n,e){var t=o.createElement("script");t.src=n,t.onload=t.onerror=function(o){t.parentNode.removeChild(t),t=null,e(n,o.type)},f.appendChild(t)}function i(n,o){n=n.push?n:[n];var e,t=n.length,i=t,u=[];for(e=function(n,e){"error"===e&&u.push(n),i-=1,0===i&&o(u)};t--;)r(n[t],e)}function u(o,e,r,u){var f,a,d;if(e&&!e.call&&(f=e),a=f?r:e,d=f?u:r,f){if(f in l)throw new Error("LoadJS: Bundle already defined");l[f]=!0}n.setTimeout(function(){i(o,function(n){n.length?(d||c)(n):(a||c)(),t(f,n)})},0)}var f=o.head,c=function(){},l={},a={},d={};u.ready=function(n,o,t){return e(n,function(n){n.length?(t||c)(n):(o||c)()}),u},u.done=function(n){t(n,[])},n.loadjs=u}(window,document); \ No newline at end of file
1
removed unnecessary script attributes from code, bumped version number
1
.js
min
mit
muicss/loadjs
10061175
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061176
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061177
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061178
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061179
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061180
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061181
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061182
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061183
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061184
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061185
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061186
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061187
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061188
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061189
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, bool initCurrentDocument = true) { return new Installation(editor, registryOptions, initCurrentDocument); } public class Installation { private IRegistryOptions _textMateRegistryOptions; private Registry _textMateRegistry; private TextEditor _editor; private TextEditorModel _editorModel; private IGrammar _grammar; private TMModel _tmModel; private TextMateColoringTransformer _transformer; public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public TextEditorModel EditorModel { get { return _editorModel; } } public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true) { _textMateRegistryOptions = registryOptions; _textMateRegistry = new Registry(registryOptions); _editor = editor; SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; if (initCurrentDocument) { OnEditorOnDocumentChanged(editor, EventArgs.Empty); } } public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { void OnEditorOnDocumentChanged(object sender, EventArgs args) { DisposeTMModel(_tmModel); _editorModel = new TextEditorModel(_editor, _editor.Document); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); } TextMateColoringTransformer GetOrCreateTransformer() } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } TextMateColoringTransformer GetOrCreateTransformer() { var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault(); if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) IGrammar _grammar; TMModel _tmModel; } } } if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Merge branch 'master' into run-unit-tests-ci <DFF> @@ -10,6 +10,11 @@ namespace AvaloniaEdit.TextMate { public static class TextMate { + public static void RegisterExceptionHandler(Action<Exception> handler) + { + _exceptionHandler = handler; + } + public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, @@ -73,13 +78,20 @@ namespace AvaloniaEdit.TextMate void OnEditorOnDocumentChanged(object sender, EventArgs args) { - DisposeTMModel(_tmModel); + try + { + DisposeTMModel(_tmModel); - _editorModel = new TextEditorModel(_editor, _editor.Document); - _tmModel = new TMModel(_editorModel); - _tmModel.SetGrammar(_grammar); - GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); - _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + _editorModel = new TextEditorModel(_editor, _editor.Document, _exceptionHandler); + _tmModel = new TMModel(_editorModel); + _tmModel.SetGrammar(_grammar); + GetOrCreateTransformer().SetModel(_editor.Document, _editor.TextArea.TextView, _tmModel); + _tmModel.AddModelTokensChangedListener(GetOrCreateTransformer()); + } + catch (Exception ex) + { + _exceptionHandler?.Invoke(ex); + } } TextMateColoringTransformer GetOrCreateTransformer() @@ -111,5 +123,7 @@ namespace AvaloniaEdit.TextMate IGrammar _grammar; TMModel _tmModel; } + + static Action<Exception> _exceptionHandler; } }
20
Merge branch 'master' into run-unit-tests-ci
6
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10061190
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061191
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061192
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061193
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061194
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061195
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061196
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061197
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061198
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061199
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061200
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061201
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061202
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061203
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061204
<NME> SelectionMouseHandler.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 Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); _mode = SelectionMode.None; if (!e.Handled) { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } } } } e.Handled = true; } #endregion #region Mouse Position <-> Text coordinates TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Fixed selection handler eating all mouse button events. <DFF> @@ -484,9 +484,9 @@ namespace AvaloniaEdit.Editing } } } - } - e.Handled = true; - } + e.Handled = true; + } + } #endregion #region Mouse Position <-> Text coordinates
3
Fixed selection handler eating all mouse button events.
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061205
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061206
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061207
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061208
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061209
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061210
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061211
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061212
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061213
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061214
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061215
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061216
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061217
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061218
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061219
<NME> TextFormatterFactory.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 AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; namespace AvaloniaEdit.Utils { { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> static class TextFormatterFactory { /// <summary> /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); var formattedText = new FormattedText( text, typeface, emSize.Value ); formattedText.SetForegroundBrush(foreground, 0, 0); return formattedText; } } } } } <MSG> Merge pull request #19 from danwalmsley/update-to-avalonia-0-5 Update to avalonia 0 5 <DFF> @@ -20,6 +20,7 @@ using System; using AvaloniaEdit.Text; using Avalonia.Controls; using Avalonia.Media; +using AvaloniaEdit.Rendering; namespace AvaloniaEdit.Utils { @@ -54,12 +55,15 @@ namespace AvaloniaEdit.Utils emSize = TextBlock.GetFontSize(element); if (foreground == null) foreground = TextBlock.GetForeground(element); - var formattedText = new FormattedText( - text, - typeface, - emSize.Value - ); - formattedText.SetForegroundBrush(foreground, 0, 0); + + var formattedText = new FormattedText + { + Text = text, + Typeface = new Typeface(typeface, emSize.Value) + }; + + formattedText.SetTextStyle(0, text.Length, foreground); + return formattedText; } }
10
Merge pull request #19 from danwalmsley/update-to-avalonia-0-5
6
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061220
<NME> fruitmachine.js <BEF> /*jslint browser:true, node:true*/ /** * FruitMachine * * Renders layouts/modules from a basic layout definition. * If views require custom interactions devs can extend * the basic functionality. * * @version 0.3.3 * @copyright The Financial Times Limited [All Rights Reserved] * @author Wilson Page <[email protected]> */ 'use strict'; /** * Module Dependencies */ var mod = require('./module'); var define = require('./define'); var utils = require('utils'); var events = require('evt'); /** * Creates a fruitmachine * * Options: * * - `Model` A model constructor to use (must have `.toJSON()`) * * @param {Object} options */ module.exports = function(options) { /** * Shortcut method for * creating lazy views. * * @param {Object} options * @return {Module} */ function fm(options) { var Module = fm.modules[options.module]; if (Module) { return new Module(options); } throw new Error("Unable to find module '" + options.module + "'"); } fm.create = module.exports; fm.Model = options.Model; fm.Events = events; fm.Module = mod(fm); fm.define = define(fm); fm.util = utils; fm.modules = {}; fm.config = { templateIterator: 'children', templateInstance: 'child' }; // Mixin events and return return events(fm); }; // `goog.inherits`, but uses a // hash of prototype properties // and class properties to be extended. View.inherit = function(protoProps, staticProps) { var parent = this; var child; } else { window['FruitMachine'] = FruitMachine; } }()); <MSG> makes more sense <DFF> @@ -1124,7 +1124,7 @@ // `goog.inherits`, but uses a // hash of prototype properties // and class properties to be extended. - View.inherit = function(protoProps, staticProps) { + View.extend = function(protoProps, staticProps) { var parent = this; var child; @@ -1172,4 +1172,5 @@ } else { window['FruitMachine'] = FruitMachine; } -}()); + +})(); \ No newline at end of file
3
makes more sense
2
.js
js
mit
ftlabs/fruitmachine
10061221
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) [![CDNJS](https://img.shields.io/cdnjs/v/loadjs.svg)](https://cdnjs.com/libraries/loadjs) ## Introduction LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 899 bytes (minified + gzipped). Here's an example of what you can do with LoadJS: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle and execute code when it loads loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); </script> ``` You can also use more advanced syntax for more options: ```html You can also use it as a CJS or AMD module: ```bash $ npm install --save-dev loadjs ``` ```javascript returnPromise: false // return Promise object (default: false) }); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(depsNotFound) { /* foobar bundle load failed */ }, }); </script> ``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) * CDNJS * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development) * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production) You can also use it as a CJS or AMD module: ```bash $ npm install --save loadjs ``` ```javascript var loadjs = require('loadjs'); loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` ## Browser Support * IE9+ (`async: false` support only works in IE10+) * Opera 12+ * Safari 5+ * Chrome * Firefox * iOS 6+ * Android 4.4+ LoadJS also detects script load failures from AdBlock Plus and Ghostery in: * Safari * Chrome Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags) ## Documentation 1. Load a single file ```javascript loadjs('/path/to/foo.js', function() { /* foo.js loaded */ }); ``` 1. Fetch files in parallel and load them asynchronously ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { /* foo.js and bar.js loaded */ }); ``` 1. Fetch JavaScript, CSS and image files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() { /* foo.css, bar.png and thunk.js loaded */ }); ``` 1. Force treat file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], function() { /* cssfile.custom loaded as stylesheet */ }); ``` 1. Force treat file as image ```javascript loadjs(['img!/path/to/image.custom'], function() { /* image.custom loaded */ }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use .ready() to define bundles and callbacks separately ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use multiple bundles in .ready() dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar'); loadjs.ready(['foo', 'bar'], function() { /* foo.js & bar1.js & bar2.js loaded */ }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { /* foo.js loaded */ }) .ready('bar', function() { /* bar.js loaded */ }); ``` 1. Use Promises to register callbacks ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true}) .then(function() { /* foo.js & bar.js loaded */ }) .catch(function(pathsNotFound) { /* at least one didn't load */ }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); } ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); // NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], function() { /* run code after dependencies have been met */ }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` 1. Implement a require-like dependency manager ```javascript var bundles = { 'bundleA': ['/file1.js', '/file2.js'], 'bundleB': ['/file3.js', '/file4.js'] }; function require(bundleIds, callbackFn) { bundleIds.forEach(function(bundleId) { if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId); }); loadjs.ready(bundleIds, callbackFn); } require(['bundleA'], function() { /* bundleA loaded */ }); require(['bundleB'], function() { /* bundleB loaded */ }); require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ }); ``` ## Directory structure <pre> loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> changed npm install --save-dev to --save <DFF> @@ -33,7 +33,7 @@ The latest version of LoadJS can be found in the `dist/` directory in this repos You can also use it as a CJS or AMD module: ```bash -$ npm install --save-dev loadjs +$ npm install --save loadjs ``` ```javascript
1
changed npm install --save-dev to --save
1
.md
md
mit
muicss/loadjs
10061222
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) [![CDNJS](https://img.shields.io/cdnjs/v/loadjs.svg)](https://cdnjs.com/libraries/loadjs) ## Introduction LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 899 bytes (minified + gzipped). Here's an example of what you can do with LoadJS: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle and execute code when it loads loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); </script> ``` You can also use more advanced syntax for more options: ```html You can also use it as a CJS or AMD module: ```bash $ npm install --save-dev loadjs ``` ```javascript returnPromise: false // return Promise object (default: false) }); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(depsNotFound) { /* foobar bundle load failed */ }, }); </script> ``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) * CDNJS * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development) * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production) You can also use it as a CJS or AMD module: ```bash $ npm install --save loadjs ``` ```javascript var loadjs = require('loadjs'); loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` ## Browser Support * IE9+ (`async: false` support only works in IE10+) * Opera 12+ * Safari 5+ * Chrome * Firefox * iOS 6+ * Android 4.4+ LoadJS also detects script load failures from AdBlock Plus and Ghostery in: * Safari * Chrome Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags) ## Documentation 1. Load a single file ```javascript loadjs('/path/to/foo.js', function() { /* foo.js loaded */ }); ``` 1. Fetch files in parallel and load them asynchronously ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { /* foo.js and bar.js loaded */ }); ``` 1. Fetch JavaScript, CSS and image files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() { /* foo.css, bar.png and thunk.js loaded */ }); ``` 1. Force treat file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], function() { /* cssfile.custom loaded as stylesheet */ }); ``` 1. Force treat file as image ```javascript loadjs(['img!/path/to/image.custom'], function() { /* image.custom loaded */ }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use .ready() to define bundles and callbacks separately ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use multiple bundles in .ready() dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar'); loadjs.ready(['foo', 'bar'], function() { /* foo.js & bar1.js & bar2.js loaded */ }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { /* foo.js loaded */ }) .ready('bar', function() { /* bar.js loaded */ }); ``` 1. Use Promises to register callbacks ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true}) .then(function() { /* foo.js & bar.js loaded */ }) .catch(function(pathsNotFound) { /* at least one didn't load */ }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); } ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); // NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], function() { /* run code after dependencies have been met */ }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` 1. Implement a require-like dependency manager ```javascript var bundles = { 'bundleA': ['/file1.js', '/file2.js'], 'bundleB': ['/file3.js', '/file4.js'] }; function require(bundleIds, callbackFn) { bundleIds.forEach(function(bundleId) { if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId); }); loadjs.ready(bundleIds, callbackFn); } require(['bundleA'], function() { /* bundleA loaded */ }); require(['bundleB'], function() { /* bundleB loaded */ }); require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ }); ``` ## Directory structure <pre> loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> changed npm install --save-dev to --save <DFF> @@ -33,7 +33,7 @@ The latest version of LoadJS can be found in the `dist/` directory in this repos You can also use it as a CJS or AMD module: ```bash -$ npm install --save-dev loadjs +$ npm install --save loadjs ``` ```javascript
1
changed npm install --save-dev to --save
1
.md
md
mit
muicss/loadjs
10061223
<NME> api.md <BEF> # API ### fruitmachine.define() slint browser:true, node:true, laxbreak:true ### fruitmachine.define() Defines a module. \nOptions: - `name {String}` the name of the module - `tag {String}` the tagName to use for the root element - `classes {Array}` a list of classes to add to the root element - `template {Function}` the template function to use when rendering - `helpers {Array}` a list of helpers to apply to the module - `initialize {Function}` custom logic to run when module instance created - `setup {Function}` custom logic to run when `.setup()` is called (directly or indirectly) - `teardown {Function}` custom logic to unbind/undo anything setup introduced (called on `.destroy()` and sometimes on `.setup()` to avoid double binding events) - `destroy {Function}` logic to permanently destroy all references ### Module#undefined shint browser:true, node:true ### Module#util Module Dependencies ### Module#exports() Exports ### Module#Module Module constructor \nOptions: - `id {String}` a unique id to query by - `model {Object|Model}` the data with which to associate this module - `tag {String}` tagName to use for the root element - `classes {Array}` list of classes to add to the root element - `template {Function}` a template to use for rendering - `helpers {Array}`a list of helper function to use on this module - `children {Object|Array}` list of child modules ### Module#add() Adds a child view(s) to another Module. \nOptions: - `at` The child index at which to insert - `inject` Injects the child's view element into the parent's - `slot` The slot at which to insert the child ### Module#remove() Removes a child view from its current Module contexts and also from the DOM unless otherwise stated. \nOptions: - `fromDOM` Whether the element should be removed from the DOM (default `true`) *Example:* // The following are equal // apple is removed from the // the view structure and DOM layout.remove(apple); apple.remove(); // Apple is removed from the // view structure, but not the DOM layout.remove(apple, { el: false }); apple.remove({ el: false }); ### Module#id() Returns a decendent module by id, or if called with no arguments, returns this view's id. \n*Example:* myModule.id(); //=> 'my_view_id' myModule.id('my_other_views_id'); //=> Module ### Module#module() Returns the first descendent Module with the passed module type. If called with no arguments the Module's own module type is returned. \n*Example:* // Assuming 'myModule' has 3 descendent // views with the module type 'apple' myModule.modules('apple'); //=> Module ### Module#modules() Returns a list of descendent Modules that match the module type given (Similar to Element.querySelectorAll();). \n*Example:* // Assuming 'myModule' has 3 descendent // views with the module type 'apple' myModule.modules('apple'); //=> [ Module, Module, Module ] ### Module#each() Calls the passed function for each of the view's children. \n*Example:* myModule.each(function(child) { // Do stuff with each child view... }); ### Module#toHTML() Templates the view, including any descendent views returning an html string. All data in the views model is made accessible to the template. \nChild views are printed into the parent template by `id`. Alternatively children can be iterated over a a list and printed with `{{{child}}}}`. *Example:* <div class="slot-1">{{{<slot>}}}</div> <div class="slot-2">{{{<slot>}}}</div> // or {{#children}} {{{child}}} {{/children}} ### Module#_innerHTML() Get the view's innerHTML ### Module#render() Renders the view and replaces the `view.el` with a freshly rendered node. \nFires a `render` event on the view. ### Module#setup() Sets up a view and all descendent views. \nSetup will be aborted if no `view.el` is found. If a view is already setup, teardown is run first to prevent a view being setup twice. Your custom `setup()` method is called Options: - `shallow` Does not recurse when `true` (default `false`) ### Module#teardown() Tearsdown a view and all descendent views that have been setup. \nYour custom `teardown` method is called and a `teardown` event is fired. Options: - `shallow` Does not recurse when `true` (default `false`) ### Module#destroy() Completely destroys a view. This means a view is torn down, removed from it's current layout context and removed from the DOM. \nYour custom `destroy` method is called and a `destroy` event is fired. NOTE: `.remove()` is only run on the view that `.destroy()` is directly called on. Options: ### Module#appendTo() Inserts the view element before the given child of the destination element. ### Module#insertBefore() Appends the view element into the destination element. Optionally specify an element to insert before. ### Module#toJSON() Provide events and lifecycle methods to fire when the element is newly associated. ### Module#inject() Empties the destination element and appends the view into it. ### Module#appendTo() Appends the view element into the destination element. ### Module#insertBefore() Inserts the view element before the given child of the destination element. ### Module#toJSON() Returns a JSON represention of a FruitMachine Module. This can be generated serverside and passed into new FruitMachine(json) to inflate serverside rendered views. ### Module#events Module Dependencies ### Module#listenerMap Local vars ### Module#on() Registers a event listener. ### Module#off() Unregisters a event listener. ### Module#fire() Fires an event on a view. <MSG> fix APi docs <DFF> @@ -200,13 +200,11 @@ and appends the view into it. ### Module#appendTo() -Inserts the view element before the given child of the destination element. +Appends the view element into the destination element. ### Module#insertBefore() -Appends the view element into -the destination element. Optionally -specify an element to insert before. +Inserts the view element before the given child of the destination element. ### Module#toJSON()
2
fix APi docs
4
.md
md
mit
ftlabs/fruitmachine
10061224
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061225
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061226
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061227
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061228
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061229
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061230
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061231
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061232
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061233
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061234
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061235
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061236
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061237
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061238
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } static string NormalizeColor(string color) { if (color.Length == 9) // convert from #RRGGBBAA to #AARRGGBB return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); return color; } { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> reduce number of allocations with normalizing color string. <DFF> @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; - using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; @@ -222,8 +221,11 @@ namespace AvaloniaEdit.TextMate static string NormalizeColor(string color) { if (color.Length == 9) - // convert from #RRGGBBAA to #AARRGGBB - return "#" + color.Substring(7, 2) + color.Substring(1, 2) + color.Substring(3, 2) + color.Substring(5, 2); + { + Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; + + return normalizedColor.ToString(); + } return color; }
5
reduce number of allocations with normalizing color string.
3
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10061239
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; 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 InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } 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 || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public void 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(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, 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> Also return the array to the pool in the Dispose method <DFF> @@ -73,6 +73,9 @@ namespace AvaloniaEdit.TextMate _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; + + if (_lineRanges != null) + ArrayPool<LineRange>.Shared.Return(_lineRanges); } public void TokenizeViewPort()
3
Also return the array to the pool in the Dispose method
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061240
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; 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 InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } 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 || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public void 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(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, 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> Also return the array to the pool in the Dispose method <DFF> @@ -73,6 +73,9 @@ namespace AvaloniaEdit.TextMate _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; + + if (_lineRanges != null) + ArrayPool<LineRange>.Shared.Return(_lineRanges); } public void TokenizeViewPort()
3
Also return the array to the pool in the Dispose method
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061241
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; 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 InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } 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 || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public void 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(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, 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> Also return the array to the pool in the Dispose method <DFF> @@ -73,6 +73,9 @@ namespace AvaloniaEdit.TextMate _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; + + if (_lineRanges != null) + ArrayPool<LineRange>.Shared.Return(_lineRanges); } public void TokenizeViewPort()
3
Also return the array to the pool in the Dispose method
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061242
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; 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 InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } 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 || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public void 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(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, 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> Also return the array to the pool in the Dispose method <DFF> @@ -73,6 +73,9 @@ namespace AvaloniaEdit.TextMate _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; + + if (_lineRanges != null) + ArrayPool<LineRange>.Shared.Return(_lineRanges); } public void TokenizeViewPort()
3
Also return the array to the pool in the Dispose method
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061243
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; 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 InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } 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 || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public void 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(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, 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> Also return the array to the pool in the Dispose method <DFF> @@ -73,6 +73,9 @@ namespace AvaloniaEdit.TextMate _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; + + if (_lineRanges != null) + ArrayPool<LineRange>.Shared.Return(_lineRanges); } public void TokenizeViewPort()
3
Also return the array to the pool in the Dispose method
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061244
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; 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 InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } 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 || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public void 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(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, 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> Also return the array to the pool in the Dispose method <DFF> @@ -73,6 +73,9 @@ namespace AvaloniaEdit.TextMate _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; + + if (_lineRanges != null) + ArrayPool<LineRange>.Shared.Return(_lineRanges); } public void TokenizeViewPort()
3
Also return the array to the pool in the Dispose method
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061245
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; 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 InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } 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 || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public void 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(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, 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> Also return the array to the pool in the Dispose method <DFF> @@ -73,6 +73,9 @@ namespace AvaloniaEdit.TextMate _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; + + if (_lineRanges != null) + ArrayPool<LineRange>.Shared.Return(_lineRanges); } public void TokenizeViewPort()
3
Also return the array to the pool in the Dispose method
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061246
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; 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 InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } 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 || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public void 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(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, 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> Also return the array to the pool in the Dispose method <DFF> @@ -73,6 +73,9 @@ namespace AvaloniaEdit.TextMate _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; + + if (_lineRanges != null) + ArrayPool<LineRange>.Shared.Return(_lineRanges); } public void TokenizeViewPort()
3
Also return the array to the pool in the Dispose method
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061247
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; 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 InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } 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 || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public void 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(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, 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> Also return the array to the pool in the Dispose method <DFF> @@ -73,6 +73,9 @@ namespace AvaloniaEdit.TextMate _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; + + if (_lineRanges != null) + ArrayPool<LineRange>.Shared.Return(_lineRanges); } public void TokenizeViewPort()
3
Also return the array to the pool in the Dispose method
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061248
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; 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 InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } 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 || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public void 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(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, 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> Also return the array to the pool in the Dispose method <DFF> @@ -73,6 +73,9 @@ namespace AvaloniaEdit.TextMate _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; + + if (_lineRanges != null) + ArrayPool<LineRange>.Shared.Return(_lineRanges); } public void TokenizeViewPort()
3
Also return the array to the pool in the Dispose method
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10061249
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; 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 InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } 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 || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public void 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(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, 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> Also return the array to the pool in the Dispose method <DFF> @@ -73,6 +73,9 @@ namespace AvaloniaEdit.TextMate _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; + + if (_lineRanges != null) + ArrayPool<LineRange>.Shared.Return(_lineRanges); } public void TokenizeViewPort()
3
Also return the array to the pool in the Dispose method
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit