This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,399 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using Unity.CodeEditor.Document;
using Unity.CodeEditor.Editing;
using Unity.CodeEditor.Platform;
using Unity.CodeEditor.Text;
using Unity.CodeEditor.Utils;
using UnityEngine;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Helper for creating a PathGeometry.
/// </summary>
internal sealed class BackgroundGeometryBuilder
{
private float _cornerRadius;
/// <summary>
/// Gets/sets the radius of the rounded corners.
/// </summary>
internal float CornerRadius {
get { return _cornerRadius; }
set { _cornerRadius = value; }
}
/// <summary>
/// Gets/Sets whether to align to whole pixels.
///
/// If BorderThickness is set to 0, the geometry is aligned to whole pixels.
/// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned
/// to whole pixels.
///
/// The default value is <c>false</c>.
/// </summary>
internal bool AlignToWholePixels { get; set; }
/// <summary>
/// Gets/sets the border thickness.
///
/// This property only has an effect if <c>AlignToWholePixels</c> is enabled.
/// When using the resulting geometry to paint a border, set this property to the border thickness.
/// Otherwise, leave the property set to the default value <c>0</c>.
/// </summary>
internal float BorderThickness { get; set; }
/// <summary>
/// Gets/Sets whether to extend the rectangles to full width at line end.
/// </summary>
internal bool ExtendToFullWidthAtLineEnd { get; set; }
/// <summary>
/// Creates a new BackgroundGeometryBuilder instance.
/// </summary>
internal BackgroundGeometryBuilder()
{
}
/// <summary>
/// Adds the specified segment to the geometry.
/// </summary>
internal void AddSegment(TextView textView, ISegment segment)
{
if (textView == null)
throw new ArgumentNullException("textView");
Vector2 pixelSize = PixelSnapHelpers.GetPixelSize(textView);
foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) {
AddRectangle(pixelSize, r);
}
}
/// <summary>
/// Adds a rectangle to the geometry.
/// </summary>
/// <remarks>
/// This overload will align the coordinates according to
/// <see cref="AlignToWholePixels"/>.
/// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned.
/// </remarks>
internal void AddRectangle(TextView textView, Rect rectangle)
{
AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle);
}
private void AddRectangle(Vector2 pixelSize, Rect r)
{
if (AlignToWholePixels) {
float halfBorder = 0.5f * BorderThickness;
AddRectangle(PixelSnapHelpers.Round(r.xMin - halfBorder, pixelSize.x) + halfBorder,
PixelSnapHelpers.Round(r.yMin - halfBorder, pixelSize.y) + halfBorder,
PixelSnapHelpers.Round(r.xMax + halfBorder, pixelSize.x) - halfBorder,
PixelSnapHelpers.Round(r.yMax + halfBorder, pixelSize.y) - halfBorder);
} else {
AddRectangle(r.xMin, r.yMin, r.xMax, r.yMax);
}
}
/// <summary>
/// Calculates the list of rectangle where the segment in shown.
/// This method usually returns one rectangle for each line inside the segment
/// (but potentially more, e.g. when bidirectional text is involved).
/// </summary>
internal static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false)
{
if (textView == null)
throw new ArgumentNullException("textView");
if (segment == null)
throw new ArgumentNullException("segment");
return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd);
}
private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd)
{
int segmentStart = segment.Offset;
int segmentEnd = segment.Offset + segment.Length;
segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength);
segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength);
TextViewPosition start;
TextViewPosition end;
if (segment is SelectionSegment) {
SelectionSegment sel = (SelectionSegment)segment;
start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn);
end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn);
} else {
start = new TextViewPosition(textView.Document.GetLocation(segmentStart));
end = new TextViewPosition(textView.Document.GetLocation(segmentEnd));
}
foreach (VisualLine vl in textView.VisualLines) {
if (vl.FirstDocumentLine.IsDeleted || vl.LastDocumentLine.IsDeleted)
continue;
int vlStartOffset = vl.FirstDocumentLine.Offset;
if (vlStartOffset > segmentEnd)
break;
int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length;
if (vlEndOffset < segmentStart)
continue;
int segmentStartVc;
if (segmentStart < vlStartOffset)
segmentStartVc = 0;
else
segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd);
int segmentEndVc;
if (segmentEnd > vlEndOffset)
segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker;
else
segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd);
foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc))
yield return rect;
}
}
/// <summary>
/// Calculates the rectangles for the visual column segment.
/// This returns one rectangle for each line inside the segment.
/// </summary>
internal static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc)
{
if (textView == null)
throw new ArgumentNullException("textView");
if (line == null)
throw new ArgumentNullException("line");
return ProcessTextLines(textView, line, startVc, endVc);
}
private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc)
{
TextLine lastTextLine = visualLine.TextLines.Last();
Vector2 scrollOffset = textView.ScrollOffset;
for (int i = 0; i < visualLine.TextLines.Count; i++) {
TextLine line = visualLine.TextLines[i];
float y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop);
int visualStartCol = visualLine.GetTextLineVisualStartColumn(line);
int visualEndCol = visualStartCol + line.Length;
if (line == lastTextLine)
visualEndCol -= 1; // 1 position for the TextEndOfParagraph
else
visualEndCol -= line.TrailingWhitespaceLength;
if (segmentEndVc < visualStartCol)
break;
if (lastTextLine != line && segmentStartVc > visualEndCol)
continue;
int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol);
int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol);
y -= scrollOffset.y;
Rect lastRect = default;
if (segmentStartVcInLine == segmentEndVcInLine) {
// GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit
// We need to return a rectangle to ensure empty lines are still visible
float pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine);
pos -= scrollOffset.x;
// The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active.
// If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace.
// Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace.
if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0)
continue;
if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0)
continue;
lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height);
} else {
if (segmentStartVcInLine <= visualEndCol) {
foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) {
float left = b.xMin - scrollOffset.x;
float right = b.xMax - scrollOffset.x;
if (lastRect != default)
yield return lastRect;
// left>right is possible in RTL languages
lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height);
}
}
}
// If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection
// after the line end.
// Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line.
if (segmentEndVc > visualEndCol) {
float left, right;
if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) {
// segmentStartVC is in virtual space
left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc);
} else {
// Otherwise, we already processed the rects from segmentStartVC up to visualEndCol,
// so we only need to do the remainder starting at visualEndCol.
// For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap,
// so we'll need to include it here.
// For the last line, visualEndCol already includes the whitespace.
left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width);
}
if (line != lastTextLine || segmentEndVc == int.MaxValue) {
// If word-wrap is enabled and the segment continues into the next line,
// or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue),
// we select the full width of the viewport.
right = textView.Bounds.x; //Math.Max((textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width);
} else {
right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc);
}
Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height);
if (lastRect != default) {
if (extendSelection.Intersects(lastRect)) {
lastRect.Union(extendSelection);
yield return lastRect;
} else {
// If the end of the line is in an RTL segment, keep lastRect and extendSelection separate.
yield return lastRect;
yield return extendSelection;
}
} else
yield return extendSelection;
} else
yield return lastRect;
}
}
private readonly PathFigures _figures = new PathFigures();
private PathFigure _figure;
private int _insertionIndex;
private float _lastTop, _lastBottom;
private float _lastLeft, _lastRight;
/// <summary>
/// Adds a rectangle to the geometry.
/// </summary>
/// <remarks>
/// This overload assumes that the coordinates are aligned properly
/// (see <see cref="AlignToWholePixels"/>).
/// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned.
/// </remarks>
internal void AddRectangle(float left, float top, float right, float bottom)
{
if (!top.IsClose(_lastBottom)) {
CloseFigure();
}
if (_figure == null) {
_figure = new PathFigure();
_figure.StartPoint = new Vector2(left, top + _cornerRadius);
if (Math.Abs(left - right) > _cornerRadius) {
_figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise));
_figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top));
_figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise));
}
_figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius));
_insertionIndex = _figure.Segments.Count;
//figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise));
} else {
if (!_lastRight.IsClose(right)) {
float cr = right < _lastRight ? -_cornerRadius : _cornerRadius;
SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise;
SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise;
_figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1));
_figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top));
_figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2));
}
_figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius));
_figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius));
if (!_lastLeft.IsClose(left)) {
float cr = left < _lastLeft ? _cornerRadius : -_cornerRadius;
SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise;
SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise;
_figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1));
_figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom));
_figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2));
}
}
this._lastTop = top;
this._lastBottom = bottom;
this._lastLeft = left;
this._lastRight = right;
}
private ArcSegment MakeArc(float x, float y, SweepDirection dir)
{
var arc = new ArcSegment
{
Point = new Vector2(x, y),
Size = new Vector2(CornerRadius, CornerRadius),
SweepDirection = dir
};
return arc;
}
private static LineSegment MakeLineSegment(float x, float y)
{
return new LineSegment { Point = new Vector2(x, y) };
}
/// <summary>
/// Closes the current figure.
/// </summary>
internal void CloseFigure()
{
if (_figure != null) {
_figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius));
if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) {
_figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise));
_figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom));
_figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise));
}
_figure.IsClosed = true;
_figures.Add(_figure);
_figure = null;
}
}
/*
/// <summary>
/// Creates the geometry.
/// Returns null when the geometry is empty!
/// </summary>
internal Geometry CreateGeometry()
{
CloseFigure();
return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null;
}
*/
/// <summary>
/// Defines the direction an which elliptical arc is drawn.
/// </summary>
internal enum SweepDirection
{
/// <summary>
/// Specifies that arcs are drawn in a counter clockwise (negative-angle) direction.
/// </summary>
CounterClockwise,
/// <summary>
/// Specifies that arcs are drawn in a clockwise (positive-angle) direction.
/// </summary>
Clockwise,
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: fa79c7e1470e47549b088019b6adeb6b
timeCreated: 1710947223
@@ -0,0 +1,68 @@
using System;
using System.Diagnostics;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Represents information about a character hit within a glyph run.
/// </summary>
/// <remarks>
/// The CharacterHit structure provides information about the index of the first
/// character that got hit as well as information about leading or trailing edge.
/// </remarks>
[DebuggerDisplay("CharacterHit({FirstCharacterIndex}, {TrailingLength})")]
internal readonly struct CharacterHit : IEquatable<CharacterHit>
{
/// <summary>
/// Initializes a new instance of the <see cref="CharacterHit"/> structure.
/// </summary>
/// <param name="firstCharacterIndex">Index of the first character that got hit.</param>
/// <param name="trailingLength">In the case of a leading edge, this value is 0. In the case of a trailing edge,
/// this value is the number of code points until the next valid caret position.</param>
[DebuggerStepThrough]
internal CharacterHit(int firstCharacterIndex, int trailingLength = 0)
{
FirstCharacterIndex = firstCharacterIndex;
TrailingLength = trailingLength;
}
/// <summary>
/// Gets the index of the first character that got hit.
/// </summary>
internal int FirstCharacterIndex { get; }
/// <summary>
/// Gets the trailing length value for the character that got hit.
/// </summary>
internal int TrailingLength { get; }
public bool Equals(CharacterHit other)
{
return FirstCharacterIndex == other.FirstCharacterIndex && TrailingLength == other.TrailingLength;
}
public override bool Equals(object obj)
{
return obj is CharacterHit other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
return FirstCharacterIndex * 397 ^ TrailingLength;
}
}
public static bool operator ==(CharacterHit left, CharacterHit right)
{
return left.Equals(right);
}
public static bool operator !=(CharacterHit left, CharacterHit right)
{
return !left.Equals(right);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f7bef4518e6241d5b7ef35e385385335
timeCreated: 1710778114
@@ -0,0 +1,102 @@
// 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.Diagnostics.CodeAnalysis;
using Unity.CodeEditor.Document;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Represents a collapsed line section.
/// Use the Uncollapse() method to uncollapse the section.
/// </summary>
internal sealed class CollapsedLineSection
{
private readonly HeightTree _heightTree;
#if DEBUG
internal string Id;
private static int _nextId;
#else
const string Id = "";
#endif
internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
{
_heightTree = heightTree;
Start = start;
End = end;
#if DEBUG
unchecked {
Id = " #" + (_nextId++);
}
#endif
}
/// <summary>
/// Gets if the document line is collapsed.
/// This property initially is true and turns to false when uncollapsing the section.
/// </summary>
internal bool IsCollapsed => Start != null;
/// <summary>
/// Gets the start line of the section.
/// When the section is uncollapsed or the text containing it is deleted,
/// this property returns null.
/// </summary>
internal DocumentLine Start { get; set; }
/// <summary>
/// Gets the end line of the section.
/// When the section is uncollapsed or the text containing it is deleted,
/// this property returns null.
/// </summary>
internal DocumentLine End { get; set; }
/// <summary>
/// Uncollapses the section.
/// This causes the Start and End properties to be set to null!
/// Does nothing if the section is already uncollapsed.
/// </summary>
internal void Uncollapse()
{
if (Start == null)
return;
if (!_heightTree.IsDisposed) {
_heightTree.Uncollapse(this);
#if DEBUG
_heightTree.CheckProperties();
#endif
}
Start = null;
End = null;
}
/// <summary>
/// Gets a string representation of the collapsed section.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public override string ToString()
{
return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null")
+ " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]";
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 57aabb9a9c3b4759aa549ef5e8bf7f07
timeCreated: 1710764034
@@ -0,0 +1,120 @@
// 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;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Base class for <see cref="IVisualLineTransformer"/> that helps
/// splitting visual elements so that colors (and other text properties) can be easily assigned
/// to individual words/characters.
/// </summary>
internal abstract class ColorizingTransformer : IVisualLineTransformer, ITextViewConnect
{
/// <summary>
/// Gets the list of elements currently being transformed.
/// </summary>
protected IList<VisualLineElement> CurrentElements { get; private set; }
/// <summary>
/// <see cref="IVisualLineTransformer.Transform"/> implementation.
/// Sets <see cref="CurrentElements"/> and calls <see cref="Colorize"/>.
/// </summary>
public void Transform(ITextRunConstructionContext context, IList<VisualLineElement> elements)
{
if (CurrentElements != null)
throw new InvalidOperationException("Recursive Transform() call");
CurrentElements = elements ?? throw new ArgumentNullException(nameof(elements));
try {
Colorize(context);
} finally {
CurrentElements = null;
}
}
/// <summary>
/// Performs the colorization.
/// </summary>
protected abstract void Colorize(ITextRunConstructionContext context);
/// <summary>
/// Changes visual element properties.
/// This method accesses <see cref="CurrentElements"/>, so it must be called only during
/// a <see cref="Transform"/> call.
/// This method splits <see cref="VisualLineElement"/>s as necessary to ensure that the region
/// can be colored by setting the <see cref="VisualLineElement.TextParagraphProperties"/> of whole elements,
/// and then calls the <paramref name="action"/> on all elements in the region.
/// </summary>
/// <param name="visualStartColumn">Start visual column of the region to change</param>
/// <param name="visualEndColumn">End visual column of the region to change</param>
/// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param>
protected void ChangeVisualElements(int visualStartColumn, int visualEndColumn, Action<VisualLineElement> action)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
for (var i = 0; i < CurrentElements.Count; i++) {
var e = CurrentElements[i];
if (e.VisualColumn > visualEndColumn)
break;
if (e.VisualColumn < visualStartColumn &&
e.VisualColumn + e.VisualLength > visualStartColumn)
{
if (e.CanSplit) {
e.Split(visualStartColumn, CurrentElements, i--);
continue;
}
}
if (e.VisualColumn >= visualStartColumn && e.VisualColumn < visualEndColumn) {
if (e.VisualColumn + e.VisualLength > visualEndColumn) {
if (e.CanSplit) {
e.Split(visualEndColumn, CurrentElements, i--);
}
} else {
action(e);
}
}
}
}
/// <summary>
/// Called when added to a text view.
/// </summary>
protected virtual void OnAddToTextView(TextView textView)
{
}
/// <summary>
/// Called when removed from a text view.
/// </summary>
protected virtual void OnRemoveFromTextView(TextView textView)
{
}
void ITextViewConnect.AddToTextView(TextView textView)
{
OnAddToTextView(textView);
}
void ITextViewConnect.RemoveFromTextView(TextView textView)
{
OnRemoveFromTextView(textView);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 68d7cf500a1a483a91877267c234c1bc
timeCreated: 1710764034
@@ -0,0 +1,98 @@
// 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 UnityEngine;
using UnityEngine.UIElements;
namespace Unity.CodeEditor.Rendering
{
internal sealed class ColumnRulerRenderer : IBackgroundRenderer
{
private Color _color;
private IEnumerable<int> _columns;
private readonly TextView _textView;
private readonly List<VisualElement> _rulerElements = new List<VisualElement>();
static readonly float DefaultThickness = 1f;
internal ColumnRulerRenderer(TextView textView)
{
_textView = textView ?? throw new ArgumentNullException(nameof(textView));
_textView.BackgroundRenderers.Add(this);
_textView.VisualLinesChanged += OnVisualLinesChanged;
}
public KnownLayer Layer => KnownLayer.Background;
internal void SetRuler(IEnumerable<int> columns, Color color)
{
_columns = columns;
_color = color;
UpdateRulerVisuals();
}
public void OnGUI(TextView textView, Rect drawingRect) { }
private void OnVisualLinesChanged(object sender, EventArgs e)
{
UpdateRulerVisuals();
}
private void UpdateRulerVisuals()
{
if (_columns == null)
{
for (int i = 0; i < _rulerElements.Count; i++)
_rulerElements[i].visible = false;
return;
}
int needed = 0;
foreach (var col in _columns)
needed++;
while (_rulerElements.Count < needed)
{
var el = new VisualElement();
el.pickingMode = PickingMode.Ignore;
el.style.position = Position.Absolute;
el.style.top = 0;
el.style.bottom = 0;
el.style.width = DefaultThickness;
_rulerElements.Add(el);
_textView.Add(el);
}
int index = 0;
foreach (var column in _columns)
{
var el = _rulerElements[index];
float xPos = _textView.WideSpaceWidth * column - _textView.HorizontalOffset;
el.style.translate = new Translate(xPos, 0, 0);
el.style.backgroundColor = _color;
el.visible = true;
index++;
}
for (int i = index; i < _rulerElements.Count; i++)
_rulerElements[i].visible = false;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 554e39bf80fd4c02a8ae0d5c3f9283a5
timeCreated: 1710779951
@@ -0,0 +1,81 @@
// 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 UnityEngine;
namespace Unity.CodeEditor.Rendering
{
internal sealed class CurrentLineHighlightRenderer : IBackgroundRenderer
{
#region Fields
private int _line;
private readonly TextView _textView;
#endregion
#region Properties
internal int Line {
get { return _line; }
set {
if (_line != value) {
_line = value;
_textView.InvalidateLayer(Layer);
}
}
}
public KnownLayer Layer => KnownLayer.Background;
internal Color BackgroundColor { get; set; } = TextEditorColors.CurrentLineBackground;
internal Color BorderColor { get; set; } = TextEditorColors.CurrentLineBorder;
#endregion
internal CurrentLineHighlightRenderer(TextView textView)
{
_textView = textView ?? throw new ArgumentNullException(nameof(textView));
_textView.BackgroundRenderers.Add(this);
_line = 0;
}
public void OnGUI(TextView textView, Rect drawingRect)
{
if (!_textView.Options.HighlightCurrentLine)
return;
var builder = new BackgroundGeometryBuilder();
var visualLine = _textView.GetVisualLine(_line);
if (visualLine == null) return;
var linePosY = visualLine.VisualTop - _textView.ScrollOffset.y;
builder.AddRectangle(textView, new Rect(0, linePosY, textView.Bounds.width, visualLine.Height));
/*var geometry = builder.CreateGeometry();
if (geometry != null) {
drawingContext.DrawGeometry(BackgroundBrush, BorderPen, geometry);
}*/
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a647d70b6a9d43e78f885cb45b2263b0
timeCreated: 1711388286
@@ -0,0 +1,96 @@
// 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.Linq;
using Unity.CodeEditor.Document;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Base class for <see cref="IVisualLineTransformer"/> that helps
/// colorizing the document. Derived classes can work with document lines
/// and text offsets and this class takes care of the visual lines and visual columns.
/// </summary>
internal abstract class DocumentColorizingTransformer : ColorizingTransformer
{
private DocumentLine _currentDocumentLine;
private int _firstLineStart;
private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset;
/// <summary>
/// Gets the current ITextRunConstructionContext.
/// </summary>
protected ITextRunConstructionContext CurrentContext { get; private set; }
/// <inheritdoc/>
protected override void Colorize(ITextRunConstructionContext context)
{
CurrentContext = context ?? throw new ArgumentNullException(nameof(context));
_currentDocumentLine = context.VisualLine.FirstDocumentLine;
_firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset;
_currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length;
var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength;
if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) {
ColorizeLine(_currentDocumentLine);
} else {
ColorizeLine(_currentDocumentLine);
// ColorizeLine modifies the visual line elements, loop through a copy of the line elements
foreach (var e in context.VisualLine.Elements.ToArray()) {
var elementOffset = _firstLineStart + e.RelativeTextOffset;
if (elementOffset >= currentDocumentLineTotalEndOffset) {
_currentDocumentLine = context.Document.GetLineByOffset(elementOffset);
_currentDocumentLineStartOffset = _currentDocumentLine.Offset;
_currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length;
currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength;
ColorizeLine(_currentDocumentLine);
}
}
}
_currentDocumentLine = null;
CurrentContext = null;
}
/// <summary>
/// Override this method to colorize an individual document line.
/// </summary>
protected abstract void ColorizeLine(DocumentLine line);
/// <summary>
/// Changes a part of the current document line.
/// </summary>
/// <param name="startOffset">Start offset of the region to change</param>
/// <param name="endOffset">End offset of the region to change</param>
/// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param>
protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action)
{
if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset)
throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset);
if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset)
throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset);
var vl = CurrentContext.VisualLine;
var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart);
var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
if (visualStart < visualEnd) {
ChangeVisualElements(visualStart, visualEnd, action);
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4c0af467cff74af5b25255706dd5dc26
timeCreated: 1710764034
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 020cf146eb6046b787fd56c275a4b6f8
timeCreated: 1710764034
@@ -0,0 +1,63 @@
// 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.Collections.Generic;
using System.Diagnostics;
namespace Unity.CodeEditor.Rendering
{
internal struct HeightTreeLineNode
{
internal HeightTreeLineNode(float height)
{
CollapsedSections = null;
Height = height;
}
internal float Height;
internal List<CollapsedLineSection> CollapsedSections;
internal bool IsDirectlyCollapsed {
get { return CollapsedSections != null; }
}
internal void AddDirectlyCollapsed(CollapsedLineSection section)
{
if (CollapsedSections == null)
CollapsedSections = new List<CollapsedLineSection>();
CollapsedSections.Add(section);
}
internal void RemoveDirectlyCollapsed(CollapsedLineSection section)
{
Debug.Assert(CollapsedSections.Contains(section));
CollapsedSections.Remove(section);
if (CollapsedSections.Count == 0)
CollapsedSections = null;
}
/// <summary>
/// Returns 0 if the line is directly collapsed, otherwise, returns <see cref="Height"/>.
/// </summary>
internal float TotalHeight {
get {
return IsDirectlyCollapsed ? 0 : Height;
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 417a7fb7b11644dcb5e6cba5fa86afd9
timeCreated: 1710764034
@@ -0,0 +1,168 @@
// 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.Collections.Generic;
using System.Diagnostics;
using Unity.CodeEditor.Document;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// A node in the text view's height tree.
/// </summary>
internal sealed class HeightTreeNode
{
internal readonly DocumentLine DocumentLine;
internal HeightTreeLineNode LineNode;
internal HeightTreeNode Left, Right, Parent;
internal bool Color;
internal HeightTreeNode()
{
}
internal HeightTreeNode(DocumentLine documentLine, float height)
{
this.DocumentLine = documentLine;
this.TotalCount = 1;
this.LineNode = new HeightTreeLineNode(height);
this.TotalHeight = height;
}
internal HeightTreeNode LeftMost {
get {
HeightTreeNode node = this;
while (node.Left != null)
node = node.Left;
return node;
}
}
internal HeightTreeNode RightMost {
get {
HeightTreeNode node = this;
while (node.Right != null)
node = node.Right;
return node;
}
}
/// <summary>
/// Gets the inorder successor of the node.
/// </summary>
internal HeightTreeNode Successor {
get {
if (Right != null) {
return Right.LeftMost;
} else {
HeightTreeNode node = this;
HeightTreeNode oldNode;
do {
oldNode = node;
node = node.Parent;
// go up until we are coming out of a left subtree
} while (node != null && node.Right == oldNode);
return node;
}
}
}
/// <summary>
/// The number of lines in this node and its child nodes.
/// Invariant:
/// totalCount = 1 + left.totalCount + right.totalCount
/// </summary>
internal int TotalCount;
/// <summary>
/// The total height of this node and its child nodes, excluding directly collapsed nodes.
/// Invariant:
/// totalHeight = left.IsDirectlyCollapsed ? 0 : left.totalHeight
/// + lineNode.IsDirectlyCollapsed ? 0 : lineNode.Height
/// + right.IsDirectlyCollapsed ? 0 : right.totalHeight
/// </summary>
internal float TotalHeight;
/// <summary>
/// List of the sections that hold this node collapsed.
/// Invariant 1:
/// For each document line in the range described by a CollapsedSection, exactly one ancestor
/// contains that CollapsedSection.
/// Invariant 2:
/// A CollapsedSection is contained either in left+middle or middle+right or just middle.
/// Invariant 3:
/// Start and end of a CollapsedSection always contain the collapsedSection in their
/// documentLine (middle node).
/// </summary>
internal List<CollapsedLineSection> CollapsedSections;
internal bool IsDirectlyCollapsed {
get {
return CollapsedSections != null;
}
}
internal void AddDirectlyCollapsed(CollapsedLineSection section)
{
if (CollapsedSections == null) {
CollapsedSections = new List<CollapsedLineSection>();
TotalHeight = 0;
}
Debug.Assert(!CollapsedSections.Contains(section));
CollapsedSections.Add(section);
}
internal void RemoveDirectlyCollapsed(CollapsedLineSection section)
{
Debug.Assert(CollapsedSections.Contains(section));
CollapsedSections.Remove(section);
if (CollapsedSections.Count == 0) {
CollapsedSections = null;
TotalHeight = LineNode.TotalHeight;
if (Left != null)
TotalHeight += Left.TotalHeight;
if (Right != null)
TotalHeight += Right.TotalHeight;
}
}
#if DEBUG
public override string ToString()
{
return "[HeightTreeNode "
+ DocumentLine.LineNumber + " CS=" + GetCollapsedSections(CollapsedSections)
+ " Line.CS=" + GetCollapsedSections(LineNode.CollapsedSections)
+ " Line.Height=" + LineNode.Height
+ " TotalHeight=" + TotalHeight
+ "]";
}
static string GetCollapsedSections(List<CollapsedLineSection> list)
{
if (list == null)
return "{}";
return "{" +
string.Join(",",
list.ConvertAll(cs => cs.Id).ToArray())
+ "}";
}
#endif
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 804b447ae94d4867aaebc623b9e491f6
timeCreated: 1710764034
@@ -0,0 +1,42 @@
// 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 UnityEngine;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Background renderers draw in the background of a known layer.
/// You can use background renderers to draw non-interactive elements on the TextView
/// without introducing new UIElements.
/// </summary>
internal interface IBackgroundRenderer
{
/// <summary>
/// Gets the layer on which this background renderer should draw.
/// </summary>
KnownLayer Layer { get; }
/// <summary>
/// Called during IMGUI repaint to draw background elements.
/// </summary>
/// <param name="textView">The text view this renderer belongs to.</param>
/// <param name="drawingRect">The visible area available for drawing, in local coordinates.</param>
void OnGUI(TextView textView, Rect drawingRect);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 999512b3c047453981fd61b8533ac1fd
timeCreated: 1710779993
@@ -0,0 +1,62 @@
// 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 Unity.CodeEditor.Document;
using Unity.CodeEditor.Utils;
#nullable enable
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Contains information relevant for text run creation.
/// </summary>
internal interface ITextRunConstructionContext
{
/// <summary>
/// Gets the text document.
/// </summary>
TextDocument Document { get; }
/// <summary>
/// Gets the text view for which the construction runs.
/// </summary>
TextView TextView { get; }
/// <summary>
/// Gets the visual line that is currently being constructed.
/// </summary>
VisualLine VisualLine { get; }
/// <summary>
/// Gets the global text run properties.
/// </summary>
TextParagraphProperties TextParagraphProperties { get; }
/// <summary>
/// Gets a piece of text from the document.
/// </summary>
/// <remarks>
/// This method is allowed to return a larger string than requested.
/// It does this by returning a <see cref="StringSegment"/> that describes the requested segment within the returned string.
/// This method should be the preferred text access method in the text transformation pipeline, as it can avoid repeatedly allocating string instances
/// for text within the same line.
/// </remarks>
StringSegment GetText(int offset, int length);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 51def9dc85f6426281d8d68f63b72425
timeCreated: 1710766477
@@ -0,0 +1,37 @@
// 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.
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Allows <see cref="VisualLineElementGenerator"/>s, <see cref="IVisualLineTransformer"/>s and
/// <see cref="IBackgroundRenderer"/>s to be notified when they are added or removed from a text view.
/// </summary>
internal interface ITextViewConnect
{
/// <summary>
/// Called when added to a text view.
/// </summary>
void AddToTextView(TextView textView);
/// <summary>
/// Called when removed from a text view.
/// </summary>
void RemoveFromTextView(TextView textView);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a89fad8b7780442baad70e115cc848a1
timeCreated: 1710764034
@@ -0,0 +1,33 @@
// 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.Collections.Generic;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Allows transforming visual line elements.
/// </summary>
internal interface IVisualLineTransformer
{
/// <summary>
/// Applies the transformation to the specified list of visual line elements.
/// </summary>
void Transform(ITextRunConstructionContext context, IList<VisualLineElement> elements);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 62395497a7ea46539f001c6080803e64
timeCreated: 1710764034
@@ -0,0 +1,80 @@
// 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 UnityEngine;
using UnityEngine.UIElements;
using Debug = System.Diagnostics.Debug;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Base class for known layers.
/// </summary>
internal class Layer : VisualElement
{
protected readonly TextView TextView;
protected readonly KnownLayer KnownLayer;
LayerPosition _Position;
readonly IMGUIContainer _backgroundIMGUIContainer;
internal Layer(TextView textView, KnownLayer knownLayer)
{
Debug.Assert(textView != null);
TextView = textView;
KnownLayer = knownLayer;
pickingMode = PickingMode.Ignore;
style.position = Position.Absolute;
style.left = 0;
style.top = 0;
style.right = 0;
style.bottom = 0; //
_backgroundIMGUIContainer = new IMGUIContainer(OnBackgroundGUI);
_backgroundIMGUIContainer.pickingMode = PickingMode.Ignore;
_backgroundIMGUIContainer.focusable = false;
_backgroundIMGUIContainer.style.position = Position.Absolute;
_backgroundIMGUIContainer.style.left = 0;
_backgroundIMGUIContainer.style.top = 0;
_backgroundIMGUIContainer.style.right = 0;
_backgroundIMGUIContainer.style.bottom = 0;
Add(_backgroundIMGUIContainer);
}
internal LayerPosition LayerPosition
{
get { return _Position; }
set { _Position = value; }
}
internal void InvalidateBackground()
{
_backgroundIMGUIContainer.MarkDirtyRepaint();
}
void OnBackgroundGUI()
{
if (Event.current.type != EventType.Repaint)
return;
if (!TextView.VisualLinesValid)
return;
TextView.RenderBackground(KnownLayer, _backgroundIMGUIContainer.contentRect);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c46fba980ad348788e35c490b31b1330
timeCreated: 1710841843
@@ -0,0 +1,91 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.CodeAnalysis;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// An enumeration of well-known layers.
/// </summary>
internal enum KnownLayer
{
/// <summary>
/// This layer is in the background.
/// There is no UIElement to represent this layer, it is directly drawn in the TextView.
/// It is not possible to replace the background layer or insert new layers below it.
/// </summary>
/// <remarks>This layer is below the Selection layer.</remarks>
Background,
/// <summary>
/// This layer contains the selection rectangle.
/// </summary>
/// <remarks>This layer is between the Background and the Text layers.</remarks>
Selection,
/// <summary>
/// This layer contains the text and inline UI elements.
/// </summary>
/// <remarks>This layer is between the Selection and the Caret layers.</remarks>
Text,
/// <summary>
/// This layer contains the blinking caret.
/// </summary>
/// <remarks>This layer is above the Text layer.</remarks>
Caret
}
/// <summary>
/// Specifies where a new layer is inserted, in relation to an old layer.
/// </summary>
internal enum LayerInsertionPosition
{
/// <summary>
/// The new layer is inserted below the specified layer.
/// </summary>
Below,
/// <summary>
/// The new layer replaces the specified layer. The old layer is removed
/// from the <see cref="TextView.Layers"/> collection.
/// </summary>
Replace,
/// <summary>
/// The new layer is inserted above the specified layer.
/// </summary>
Above
}
internal sealed class LayerPosition : IComparable<LayerPosition>
{
internal readonly KnownLayer KnownLayer;
internal readonly LayerInsertionPosition Position;
internal LayerPosition(KnownLayer knownLayer, LayerInsertionPosition position)
{
KnownLayer = knownLayer;
Position = position;
}
[SuppressMessage("ReSharper", "ImpureMethodCallOnReadonlyValueField")]
public int CompareTo(LayerPosition other)
{
var r = KnownLayer.CompareTo(other.KnownLayer);
return r != 0 ? r : Position.CompareTo(other.Position);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: be0c6030e24d4c9ea8bb60d258e05588
timeCreated: 1710780021
@@ -0,0 +1,191 @@
// 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.Text.RegularExpressions;
namespace Unity.CodeEditor.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
// cached regex match to avoid re-running the regex on every sweep iteration
private Match _cachedMatch;
private int _cachedMatchOffset; // document offset of the cached match, or -1 if no match
private bool _hasCachedMatch;
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
internal bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
internal override void StartGeneration(ITextRunConstructionContext context)
{
base.StartGeneration(context);
_cachedMatch = null;
_cachedMatchOffset = -1;
_hasCachedMatch = false;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
if (_hasCachedMatch)
{
if (_cachedMatchOffset == -1)
{
// no match exists on this line at all — skip the regex entirely
matchOffset = -1;
return _cachedMatch;
}
if (startOffset <= _cachedMatchOffset)
{
// the cached match is still the first match at or after startOffset
matchOffset = _cachedMatchOffset;
return _cachedMatch;
}
// startOffset moved past the cached match — need to re-run
}
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
// Cache for subsequent calls
_hasCachedMatch = true;
_cachedMatch = m;
_cachedMatchOffset = matchOffset;
return m;
}
/// <inheritdoc/>
internal override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
internal override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
var targetUrl = "mailto:" + match.Value;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 19c0616fcade47d78aaa68d248a445e3
timeCreated: 1710764034
@@ -0,0 +1,45 @@
// 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 Unity.CodeEditor.Text;
namespace Unity.CodeEditor.Rendering
{
internal sealed class SimpleTextSource : TextFormatter.ITextSource
{
private readonly string _text;
private readonly TextParagraphProperties _properties;
internal SimpleTextSource(string text, TextParagraphProperties properties)
{
_text = text;
_properties = properties;
}
public TextRun GetTextRun(int textSourceCharacterIndex)
{
if (textSourceCharacterIndex < _text.Length)
return new StringTextRun(
_text.Substring(textSourceCharacterIndex,
_text.Length - textSourceCharacterIndex), _properties);
return new TextEndOfParagraph(1, _properties);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 3d90656409b04b918d9e0abfefbc39df
timeCreated: 1711021268
@@ -0,0 +1,232 @@
// 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.Diagnostics.CodeAnalysis;
using Unity.CodeEditor.Document;
using Unity.CodeEditor.Text;
using Document_LogicalDirection = Unity.CodeEditor.Document.LogicalDirection;
using LogicalDirection = Unity.CodeEditor.Document.LogicalDirection;
namespace Unity.CodeEditor.Rendering
{
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Element generator that displays · for spaces and » for tabs and a box for control characters.
/// </summary>
/// <remarks>
/// This element generator is present in every TextView by default; the enabled features can be configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")]
internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
/// <summary>
/// Gets/Sets whether to show · for spaces.
/// </summary>
internal bool ShowSpaces { get; set; }
/// <summary>
/// Gets/Sets whether to show » for tabs.
/// </summary>
internal bool ShowTabs { get; set; }
// precomputed offsets of spaces/tabs for the current line
// built once in StartGeneration, then GetFirstInterestedOffset
// just walks the cursor — O(1) per call instead of scanning text.
private int[] _interestingOffsets;
private int _interestingOffsetCount;
private int _interestingOffsetCursor;
/// <summary>
/// Creates a new SingleCharacterElementGenerator instance.
/// </summary>
public SingleCharacterElementGenerator()
{
ShowSpaces = true;
ShowTabs = true;
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
ShowSpaces = options.ShowSpaces;
ShowTabs = options.ShowTabs;
}
internal override void StartGeneration(ITextRunConstructionContext context)
{
base.StartGeneration(context);
var firstLine = context.VisualLine.FirstDocumentLine;
var lineStart = firstLine.Offset;
var relevantText = context.GetText(lineStart, firstLine.EndOffset - lineStart);
// reuse array if large enough, otherwise allocate
if (_interestingOffsets == null || _interestingOffsets.Length < relevantText.Count)
_interestingOffsets = new int[relevantText.Count];
_interestingOffsetCount = 0;
for (var i = 0; i < relevantText.Count; i++)
{
var c = relevantText.Text[relevantText.Offset + i];
if ((ShowSpaces && c == ' ') || c == '\t')
{
_interestingOffsets[_interestingOffsetCount++] = lineStart + i;
}
}
_interestingOffsetCursor = 0;
}
internal override int GetFirstInterestedOffset(int startOffset)
{
// advance cursor past offsets before startOffset
while (_interestingOffsetCursor < _interestingOffsetCount
&& _interestingOffsets[_interestingOffsetCursor] < startOffset)
{
_interestingOffsetCursor++;
}
if (_interestingOffsetCursor < _interestingOffsetCount)
{
return _interestingOffsets[_interestingOffsetCursor];
}
return -1;
}
internal override VisualLineElement ConstructElement(int offset)
{
var c = CurrentContext.Document.GetCharAt(offset);
if (ShowSpaces && c == ' ')
{
// put consecutive spaces to batch into a single element
int spaceCount = 1;
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
while (offset + spaceCount < endOffset
&& CurrentContext.Document.GetCharAt(offset + spaceCount) == ' ')
{
spaceCount++;
}
var runProperties = CurrentContext.TextParagraphProperties.Clone();
runProperties.SetForegroundColor(CurrentContext.TextView.NonPrintableCharacterColor);
return new SpaceTextElement(
CurrentContext.TextView.Options.ShowSpacesGlyph,
spaceCount,
runProperties);
}
else if (c == '\t')
{
var runProperties = CurrentContext.TextParagraphProperties.Clone();
runProperties.SetForegroundColor(CurrentContext.TextView.NonPrintableCharacterColor);
return new TabTextElement(
CurrentContext.TextView.Options.ShowTabsGlyph,
CurrentContext.TextView.Options.IndentationSize,
ShowTabs,
runProperties);
}
return null;
}
private sealed class SpaceTextElement : VisualLineElement
{
string _spaceString;
TextParagraphProperties _spaceParagraphProperties;
internal SpaceTextElement(string spaceGlyph, int spaceCount, TextParagraphProperties properties)
: base(spaceGlyph.Length * spaceCount, spaceCount)
{
if (spaceCount == 1)
_spaceString = spaceGlyph;
else if (spaceGlyph.Length == 1)
_spaceString = new string(spaceGlyph[0], spaceCount);
else
{
var sb = new System.Text.StringBuilder(spaceGlyph.Length * spaceCount);
for (int i = 0; i < spaceCount; i++)
sb.Append(spaceGlyph);
_spaceString = sb.ToString();
}
_spaceParagraphProperties = properties;
}
internal override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
return new StringTextRun(_spaceString, _spaceParagraphProperties);
}
internal override int GetNextCaretPosition(int visualColumn, Document_LogicalDirection direction,
CaretPositioningMode mode)
{
if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
return base.GetNextCaretPosition(visualColumn, direction, mode);
else
return -1;
}
internal override bool IsWhitespace(int visualColumn)
{
return true;
}
}
private sealed class TabTextElement : VisualLineElement
{
string _tabString;
TextParagraphProperties _tabParagraphProperties;
internal TabTextElement(string tabGlyph, int tabSize, bool showTabs, TextParagraphProperties properties) : base(tabSize, 1)
{
_tabString = GenerateTabText(tabSize, tabGlyph, showTabs);
_tabParagraphProperties = properties;
}
internal override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
return new TabTextRun(_tabString, _tabParagraphProperties);
}
internal override int GetNextCaretPosition(int visualColumn, Document_LogicalDirection direction,
CaretPositioningMode mode)
{
if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
return base.GetNextCaretPosition(visualColumn, direction, mode);
else
return -1;
}
internal override bool IsWhitespace(int visualColumn)
{
return true;
}
static string GenerateTabText(int tabSize, string tabGlyph, bool showTabs)
{
if (showTabs)
{
return string.Concat(tabGlyph,
new string(' ', tabSize - tabGlyph.Length));
}
return new string(' ', tabSize);
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e50698d1043640dc8ef26d6236f48f1b
timeCreated: 1711019797
@@ -0,0 +1,86 @@
// 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.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.CodeEditor.Rendering
{
internal sealed class TextLayer : Layer
{
internal int Index;
private readonly List<VisualLineDrawingVisual> _visuals = new List<VisualLineDrawingVisual>();
private readonly IMGUIContainer _imguiContainer;
internal TextLayer(TextView textView) : base(textView, KnownLayer.Text)
{
_imguiContainer = new IMGUIContainer(OnGUI);
_imguiContainer.pickingMode = PickingMode.Ignore;
_imguiContainer.focusable = false;
_imguiContainer.style.position = Position.Absolute;
_imguiContainer.style.left = 0;
_imguiContainer.style.top = 0;
_imguiContainer.style.right = 0;
_imguiContainer.style.bottom = 0;
Add(_imguiContainer);
}
internal void SetVisualLines(ICollection<VisualLine> visualLines)
{
_visuals.Clear();
foreach (var newLine in visualLines)
{
var visual = newLine.Render();
_visuals.Add(visual);
}
ArrangeVisuals();
_imguiContainer.MarkDirtyRepaint();
}
private void OnGUI()
{
if (Event.current.type != EventType.Repaint)
return;
foreach (var visual in _visuals)
{
float pos = 0;
foreach (var textLine in visual.VisualLine.TextLines)
{
float x = Mathf.Round(visual.RenderTransform.x);
float y = Mathf.Round(pos + visual.RenderTransform.y);
var guiStyle = textLine.TextParagraphProperties.GUIStyle;
var rect = new Rect(x, y, _imguiContainer.contentRect.width - x, textLine.Height);
guiStyle.Draw(rect, textLine.MarkupGUIContent, false, false, false, false);
pos += textLine.Height;
}
}
}
void ArrangeVisuals()
{
TextView.ArrangeTextLayer(_visuals);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: ab79da1819734438b1c811b17845aae6
timeCreated: 1710841790
@@ -0,0 +1,91 @@
using UnityEngine;
namespace Unity.CodeEditor.Rendering
{
internal class TextParagraphProperties
{
private readonly double _tabSize;
private readonly bool _textWrapping;
private readonly GUIStyle _guiStyle;
internal TextParagraphProperties Clone()
{
TextParagraphProperties result = new TextParagraphProperties(
TextWrapping,
TabSize,
Font,
FontSize,
ForegroundColor);
return result;
}
internal bool TextWrapping
{
get { return _textWrapping; }
}
internal double TabSize
{
get { return _tabSize; }
}
internal Font Font
{
get { return _guiStyle.font; }
}
internal int FontSize
{
get { return _guiStyle.fontSize; }
}
internal Color ForegroundColor
{
get { return _guiStyle.normal.textColor; }
}
internal GUIStyle GUIStyle
{
get { return _guiStyle; }
}
internal float Leading { get; set; } = 2;
internal bool FirstLineInParagraph { get; set; }
internal double Indent { get; set; }
internal void SetForegroundColor(Color foreground)
{
if (foreground.r == 0 && foreground.g == 0 && foreground.b == 0 && foreground.a == 0)
{
_guiStyle.normal.textColor = TextEditorColors.DefaultText;
return;
}
_guiStyle.normal.textColor = foreground;
}
internal TextParagraphProperties(
bool textWrapping,
double tabSize,
Font font,
int fontSize,
Color foregroundColor)
{
_tabSize = tabSize;
_textWrapping = textWrapping;
_guiStyle = new GUIStyle()
{
wordWrap = false,
font = font,
fontSize = fontSize,
normal =
{
textColor = foregroundColor,
},
richText = true,
};
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2c47049c0f9b47c1840bda2ed3283ae7
timeCreated: 1710837992
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 98a412a8c1a2436db3a14378542ffe03
timeCreated: 1710764480
@@ -0,0 +1,62 @@
// 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 Unity.CodeEditor.Utils;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Contains weak event managers for the TextView events.
/// </summary>
internal static class TextViewWeakEventManager
{
/// <summary>
/// Weak event manager for the <see cref="TextView.DocumentChanged"/> event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal sealed class DocumentChanged : WeakEventManagerBase<DocumentChanged, TextView, EventHandler, EventArgs>
{
protected override void StartListening(TextView source) => source.DocumentChanged += DeliverEvent;
protected override void StopListening(TextView source) => source.DocumentChanged -= DeliverEvent;
}
/// <summary>
/// Weak event manager for the <see cref="TextView.VisualLinesChanged"/> event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal sealed class VisualLinesChanged : WeakEventManagerBase<VisualLinesChanged, TextView, EventHandler, EventArgs>
{
protected override void StartListening(TextView source) => source.VisualLinesChanged += DeliverEvent;
protected override void StopListening(TextView source) => source.VisualLinesChanged -= DeliverEvent;
}
/// <summary>
/// Weak event manager for the <see cref="TextView.ScrollOffsetChanged"/> event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
internal sealed class ScrollOffsetChanged : WeakEventManagerBase<ScrollOffsetChanged, TextView, EventHandler, EventArgs>
{
protected override void StartListening(TextView source) => source.ScrollOffsetChanged += DeliverEvent;
protected override void StopListening(TextView source) => source.ScrollOffsetChanged -= DeliverEvent;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 187e79737b0d4cafb4c958f89f9f6843
timeCreated: 1710764034
@@ -0,0 +1,790 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Unity.CodeEditor.Document;
using Unity.CodeEditor.Text;
using Unity.CodeEditor.Utils;
using UnityEngine;
using Debug = System.Diagnostics.Debug;
using LogicalDirection = Unity.CodeEditor.Document.LogicalDirection;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
internal sealed class VisualLine
{
internal const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
internal TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
internal DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
internal DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
internal ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
internal ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
internal int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
internal int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
internal int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
internal float Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
internal float VisualTop { get; set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var textParagraphProperties = context.TextParagraphProperties;
foreach (var element in _elements)
{
element.SetTextParagraphProperties(textParagraphProperties);
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
internal void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
internal void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
internal int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
internal int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
internal TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
internal TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
internal float GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var pos = VisualTop;
foreach (var tl in TextLines)
{
if (tl == textLine)
{
switch (yPositionMode)
{
case VisualYPosition.LineTop:
return pos;
case VisualYPosition.LineMiddle:
return pos + tl.Height / 2;
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.LineRect.yMin - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.LineRect.yMin - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.LineRect.yMin - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.LineRect.yMin;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
internal int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
internal TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
internal Vector2 GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Vector2(xPos, yPos);
}
internal Vector2 GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Vector2(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
internal float GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
internal int GetVisualColumn(Vector2 point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
internal int GetVisualColumn(Vector2 point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.y), point.x, allowVirtualSpace);
}
internal int GetVisualColumn(Vector2 point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.y);
var vc = GetVisualColumn(textLine, point.x, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
internal int GetVisualColumn(TextLine textLine, float xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
internal int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
internal int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
internal int GetVisualColumnFloor(Vector2 point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
internal int GetVisualColumnFloor(Vector2 point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Vector2 point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.y);
if (point.x > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.x - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.x);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
internal TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <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>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
internal TextViewPosition GetTextViewPosition(Vector2 visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <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>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
internal TextViewPosition GetTextViewPositionFloor(Vector2 visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
internal bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
internal int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual
{
internal VisualLine VisualLine { get; }
internal float LineHeight { get; }
internal bool IsAdded { get; set; }
internal Vector2 RenderTransform { get; set; }
internal VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
// Rendering is now handled by TextLayer which creates Label elements for each line.
// This class just stores the layout/transform information.
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 53017b1654c74ad599aa144268eff7fc
timeCreated: 1710766756
@@ -0,0 +1,42 @@
// 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 Unity.CodeEditor.Document;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// EventArgs for the <see cref="TextView.VisualLineConstructionStarting"/> event.
/// </summary>
internal class VisualLineConstructionStartEventArgs : EventArgs
{
/// <summary>
/// Gets/Sets the first line that is visible in the TextView.
/// </summary>
internal DocumentLine FirstLineInView { get; }
/// <summary>
/// Creates a new VisualLineConstructionStartEventArgs instance.
/// </summary>
internal VisualLineConstructionStartEventArgs(DocumentLine firstLineInView)
{
FirstLineInView = firstLineInView ?? throw new ArgumentNullException(nameof(firstLineInView));
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: dcf41b8eb4864b26940bbaae32dedbb4
timeCreated: 1710764034
@@ -0,0 +1,264 @@
// 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.Diagnostics.CodeAnalysis;
using Unity.CodeEditor.Document;
using Unity.CodeEditor.Text;
using UnityEngine;
using LogicalDirection = Unity.CodeEditor.Document.LogicalDirection;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Represents a visual element in the document.
/// </summary>
internal abstract class VisualLineElement
{
/// <summary>
/// Creates a new VisualLineElement.
/// </summary>
/// <param name="visualLength">The length of the element in VisualLine coordinates. Must be positive.</param>
/// <param name="documentLength">The length of the element in the document. Must be non-negative.</param>
protected VisualLineElement(int visualLength, int documentLength)
{
if (visualLength < 1)
throw new ArgumentOutOfRangeException(nameof(visualLength), visualLength, "Value must be at least 1");
if (documentLength < 0)
throw new ArgumentOutOfRangeException(nameof(documentLength), documentLength, "Value must be at least 0");
VisualLength = visualLength;
DocumentLength = documentLength;
}
/// <summary>
/// Gets the length of this element in visual columns.
/// </summary>
internal int VisualLength { get; private set; }
/// <summary>
/// Gets the length of this element in the text document.
/// </summary>
internal int DocumentLength { get; private set; }
/// <summary>
/// Gets the visual column where this element starts.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods",
Justification = "This property holds the start visual column, use GetVisualColumn to get inner visual columns.")]
internal int VisualColumn { get; set; }
/// <summary>
/// Gets the text offset where this element starts, relative to the start text offset of the visual line.
/// </summary>
internal int RelativeTextOffset { get; set; }
/// <summary>
/// Gets the text run properties.
/// A unique <see cref="VisualLineElementTextRunProperties"/> instance is used for each
/// <see cref="VisualLineElement"/>; colorizing code may assume that modifying the
/// <see cref="VisualLineElementTextRunProperties"/> will affect only this
/// <see cref="VisualLineElement"/>.
/// </summary>
internal TextParagraphProperties TextParagraphProperties { get; private set; }
/// <summary>
/// Gets/sets the brush used for the background of this <see cref="VisualLineElement" />.
/// </summary>
internal Color BackgroundColor { get; set; }
internal void SetTextParagraphProperties(TextParagraphProperties p)
{
TextParagraphProperties = p;
}
/// <summary>
/// Creates the TextRun for this line element.
/// </summary>
/// <param name="startVisualColumn">
/// The visual column from which the run should be constructed.
/// Normally the same value as the <see cref="VisualColumn"/> property is used to construct the full run;
/// but when word-wrapping is active, partial runs might be created.
/// </param>
/// <param name="context">
/// Context object that contains information relevant for text run creation.
/// </param>
internal abstract TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context);
/// <summary>
/// Retrieves the text span immediately before the visual column.
/// </summary>
/// <remarks>This method is used for word-wrapping in bidirectional text.</remarks>
internal virtual ReadOnlyMemory<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context)
{
return ReadOnlyMemory<char>.Empty;
}
/// <summary>
/// Gets if this VisualLineElement can be split.
/// </summary>
internal virtual bool CanSplit => false;
/// <summary>
/// Splits the element.
/// </summary>
/// <param name="splitVisualColumn">Position inside this element at which it should be broken</param>
/// <param name="elements">The collection of line elements</param>
/// <param name="elementIndex">The index at which this element is in the elements list.</param>
internal virtual void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex)
{
throw new NotSupportedException();
}
/// <summary>
/// Helper method for splitting this line element into two, correctly updating the
/// <see cref="VisualLength"/>, <see cref="DocumentLength"/>, <see cref="VisualColumn"/>
/// and <see cref="RelativeTextOffset"/> properties.
/// </summary>
/// <param name="firstPart">The element before the split position.</param>
/// <param name="secondPart">The element after the split position.</param>
/// <param name="splitVisualColumn">The split position as visual column.</param>
/// <param name="splitRelativeTextOffset">The split position as text offset.</param>
protected void SplitHelper(VisualLineElement firstPart, VisualLineElement secondPart, int splitVisualColumn, int splitRelativeTextOffset)
{
if (firstPart == null)
throw new ArgumentNullException(nameof(firstPart));
if (secondPart == null)
throw new ArgumentNullException(nameof(secondPart));
var relativeSplitVisualColumn = splitVisualColumn - VisualColumn;
var relativeSplitRelativeTextOffset = splitRelativeTextOffset - RelativeTextOffset;
if (relativeSplitVisualColumn <= 0 || relativeSplitVisualColumn >= VisualLength)
throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1));
if (relativeSplitRelativeTextOffset < 0 || relativeSplitRelativeTextOffset > DocumentLength)
throw new ArgumentOutOfRangeException(nameof(splitRelativeTextOffset), splitRelativeTextOffset, "Value must be between " + (RelativeTextOffset) + " and " + (RelativeTextOffset + DocumentLength));
var oldVisualLength = VisualLength;
var oldDocumentLength = DocumentLength;
var oldVisualColumn = VisualColumn;
var oldRelativeTextOffset = RelativeTextOffset;
firstPart.VisualColumn = oldVisualColumn;
secondPart.VisualColumn = oldVisualColumn + relativeSplitVisualColumn;
firstPart.RelativeTextOffset = oldRelativeTextOffset;
secondPart.RelativeTextOffset = oldRelativeTextOffset + relativeSplitRelativeTextOffset;
firstPart.VisualLength = relativeSplitVisualColumn;
secondPart.VisualLength = oldVisualLength - relativeSplitVisualColumn;
firstPart.DocumentLength = relativeSplitRelativeTextOffset;
secondPart.DocumentLength = oldDocumentLength - relativeSplitRelativeTextOffset;
if (firstPart.TextParagraphProperties == null)
firstPart.TextParagraphProperties = TextParagraphProperties.Clone();
if (secondPart.TextParagraphProperties == null)
secondPart.TextParagraphProperties = TextParagraphProperties.Clone();
firstPart.BackgroundColor = BackgroundColor;
secondPart.BackgroundColor = BackgroundColor;
}
/// <summary>
/// Gets the visual column of a text location inside this element.
/// The text offset is given relative to the visual line start.
/// </summary>
internal virtual int GetVisualColumn(int relativeTextOffset)
{
if (relativeTextOffset >= RelativeTextOffset + DocumentLength)
return VisualColumn + VisualLength;
return VisualColumn;
}
/// <summary>
/// Gets the text offset of a visual column inside this element.
/// </summary>
/// <returns>A text offset relative to the visual line start.</returns>
internal virtual int GetRelativeOffset(int visualColumn)
{
if (visualColumn >= VisualColumn + VisualLength)
return RelativeTextOffset + DocumentLength;
return RelativeTextOffset;
}
/// <summary>
/// Gets the next caret position inside this element.
/// </summary>
/// <param name="visualColumn">The visual column from which the search should be started.</param>
/// <param name="direction">The search direction (forwards or backwards).</param>
/// <param name="mode">Whether to stop only at word borders.</param>
/// <returns>The visual column of the next caret position, or -1 if there is no next caret position.</returns>
/// <remarks>
/// In the space between two line elements, it is sufficient that one of them contains a caret position;
/// though in many cases, both of them contain one.
/// </remarks>
internal virtual int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
{
var stop1 = VisualColumn;
var stop2 = VisualColumn + VisualLength;
if (direction == LogicalDirection.Backward)
{
if (visualColumn > stop2 && mode != CaretPositioningMode.WordStart && mode != CaretPositioningMode.WordStartOrSymbol)
return stop2;
if (visualColumn > stop1)
return stop1;
} else
{
if (visualColumn < stop1)
return stop1;
if (visualColumn < stop2 && mode != CaretPositioningMode.WordStart && mode != CaretPositioningMode.WordStartOrSymbol)
return stop2;
}
return -1;
}
/// <summary>
/// Gets whether the specified offset in this element is considered whitespace.
/// </summary>
internal virtual bool IsWhitespace(int visualColumn)
{
return false;
}
/// <summary>
/// Gets whether the <see cref="GetNextCaretPosition"/> implementation handles line borders.
/// If this property returns false, the caller of GetNextCaretPosition should handle the line
/// borders (i.e. place caret stops at the start and end of the line).
/// This property has an effect only for VisualLineElements that are at the start or end of a
/// <see cref="VisualLine"/>.
/// </summary>
internal virtual bool HandlesLineBorders => false;
/*
/// <summary>
/// Queries the cursor over the visual line element.
/// </summary>
protected internal virtual void OnQueryCursor(PointerEventArgs e)
{
}*/
/// <summary>
/// Allows the visual line element to handle a pointer event.
/// </summary>
protected internal virtual void OnPointerPressed(Vector2 localPosition)
{
}
/// <summary>
/// Allows the visual line element to handle a pointer event.
/// </summary>
protected internal virtual void OnPointerReleased(Vector2 localPosition)
{
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d90fa08383d64773aa221be3f519db0d
timeCreated: 1710766448
@@ -0,0 +1,76 @@
// 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;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// Abstract base class for generators that produce new visual line elements.
/// </summary>
internal abstract class VisualLineElementGenerator
{
/// <summary>
/// Gets the text run construction context.
/// </summary>
protected ITextRunConstructionContext CurrentContext { get; private set; }
/// <summary>
/// Initializes the generator for the <see cref="ITextRunConstructionContext"/>
/// </summary>
internal virtual void StartGeneration(ITextRunConstructionContext context)
{
CurrentContext = context ?? throw new ArgumentNullException(nameof(context));
}
/// <summary>
/// De-initializes the generator.
/// </summary>
internal virtual void FinishGeneration()
{
CurrentContext = null;
}
/// <summary>
/// Should only be used by VisualLine.ConstructVisualElements.
/// </summary>
internal int CachedInterest;
/// <summary>
/// Gets the first offset >= startOffset where the generator wants to construct an element.
/// Return -1 to signal no interest.
/// </summary>
internal abstract int GetFirstInterestedOffset(int startOffset);
/// <summary>
/// Constructs an element at the specified offset.
/// May return null if no element should be constructed.
/// </summary>
/// <remarks>
/// Avoid signalling interest and then building no element by returning null - doing so
/// causes the generated <see cref="VisualLineText"/> elements to be unnecessarily split
/// at the position where you signalled interest.
/// </remarks>
internal abstract VisualLineElement ConstructElement(int offset);
}
internal interface IBuiltinElementGenerator
{
void FetchOptions(TextEditorOptions options);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 46c07c86cb754c3a9e8b5c018ec0b12b
timeCreated: 1710764034
@@ -0,0 +1,56 @@
// TO COMPLETE
// 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;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// VisualLineElement that represents a piece of text and is a clickable link.
/// </summary>
internal class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
internal Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
internal string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
internal bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
internal VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a1f4f3bdae774bc3b98ecd20cfe488d2
timeCreated: 1710767095
@@ -0,0 +1,133 @@
// TO COMPLETE
// 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 Unity.CodeEditor.Document;
using Unity.CodeEditor.Text;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// VisualLineElement that represents a piece of text.
/// </summary>
internal class VisualLineText : VisualLineElement
{
/// <summary>
/// Gets the parent visual line.
/// </summary>
internal VisualLine ParentVisualLine { get; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
internal VisualLineText(VisualLine parentVisualLine, int length) : base(length, length)
{
ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine));
}
/// <summary>
/// Override this method to control the type of new VisualLineText instances when
/// the visual line is split due to syntax highlighting.
/// </summary>
protected virtual VisualLineText CreateInstance(int length)
{
return new VisualLineText(ParentVisualLine, length);
}
/// <inheritdoc/>
internal override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
var relativeOffset = startVisualColumn - VisualColumn;
var offset = context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset + relativeOffset;
var text = context.GetText(
offset,
DocumentLength - relativeOffset);
return new StringSegmentTextRun(text, TextParagraphProperties);
}
/// <inheritdoc/>
internal override bool IsWhitespace(int visualColumn)
{
var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset;
return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset));
}
internal override ReadOnlyMemory<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
var relativeOffset = visualColumnLimit - VisualColumn;
var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset);
return text.Text.AsMemory().Slice(text.Offset, text.Count);
}
/// <inheritdoc/>
internal override bool CanSplit => true;
/// <inheritdoc/>
internal override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex)
{
if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength)
throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1));
if (elements == null)
throw new ArgumentNullException(nameof(elements));
if (elements[elementIndex] != this)
throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index");
var relativeSplitPos = splitVisualColumn - VisualColumn;
var splitPart = CreateInstance(DocumentLength - relativeSplitPos);
SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset);
elements.Insert(elementIndex + 1, splitPart);
}
/// <inheritdoc/>
internal override int GetRelativeOffset(int visualColumn)
{
return RelativeTextOffset + visualColumn - VisualColumn;
}
/// <inheritdoc/>
internal override int GetVisualColumn(int relativeTextOffset)
{
return VisualColumn + relativeTextOffset - RelativeTextOffset;
}
/// <inheritdoc/>
internal override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
{
var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset;
var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode);
if (pos < textOffset || pos > textOffset + DocumentLength)
return -1;
return VisualColumn + pos - textOffset;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: db01cc38c298426b83c5ddd52dca39a5
timeCreated: 1710767170
@@ -0,0 +1,121 @@
using System;
using Unity.CodeEditor.Document;
using Unity.CodeEditor.Text;
using Unity.CodeEditor.Utils;
using UnityEngine;
namespace Unity.CodeEditor.Rendering
{
internal class VisualLineTextSource : ITextRunConstructionContext, TextFormatter.ITextSource
{
public VisualLineTextSource(VisualLine visualLine)
{
VisualLine = visualLine;
}
public VisualLine VisualLine { get; private set; }
public TextView TextView { get; set; }
public TextDocument Document { get; set; }
public TextParagraphProperties TextParagraphProperties { get; set; }
private int _lastElementIndex;
public TextRun GetTextRun(int textSourceCharacterIndex)
{
try {
var elements = VisualLine.Elements;
// start scanning from the cached position instead of 0
for (int i = _lastElementIndex; i < elements.Count; i++) {
var element = elements[i];
if (textSourceCharacterIndex >= element.VisualColumn
&& textSourceCharacterIndex < element.VisualColumn + element.VisualLength) {
_lastElementIndex = i;
int relativeOffset = textSourceCharacterIndex - element.VisualColumn;
TextRun run = element.CreateTextRun(textSourceCharacterIndex, this);
if (run == null)
throw new ArgumentNullException(element.GetType().Name + ".CreateTextRun");
if (run.Length == 0)
throw new ArgumentException("The returned TextRun must not have length 0.", element.GetType().Name + ".Length");
if (relativeOffset + run.Length > element.VisualLength)
throw new ArgumentException("The returned TextRun is too long.", element.GetType().Name + ".CreateTextRun");
/*if (run is InlineObjectRun inlineRun) {
inlineRun.VisualLine = VisualLine;
VisualLine.HasInlineObjects = true;
TextView.AddInlineObject(inlineRun);
}*/
return run;
}
}
if (TextView.Options.ShowEndOfLine && textSourceCharacterIndex == VisualLine.VisualLength && VisualLine.LastDocumentLine.DelimiterLength > 0) {
return CreateTextRunForNewLine();
}
return new TextEndOfParagraph(1, TextParagraphProperties);
} catch (Exception ex) {
Debug.Log(ex.ToString());
throw;
}
}
private TextRun CreateTextRunForNewLine()
{
string newlineText = "";
DocumentLine lastDocumentLine = VisualLine.LastDocumentLine;
if (lastDocumentLine.DelimiterLength == 2)
{
newlineText = TextView.Options.EndOfLineCRLFGlyph;
}
else if (lastDocumentLine.DelimiterLength == 1)
{
char newlineChar = Document.GetCharAt(lastDocumentLine.Offset + lastDocumentLine.Length);
if (newlineChar == '\r')
newlineText = TextView.Options.EndOfLineCRGlyph;
else if (newlineChar == '\n')
newlineText = TextView.Options.EndOfLineLFGlyph;
else
newlineText = "?";
}
var p = TextParagraphProperties.Clone();
p.SetForegroundColor(TextView.NonPrintableCharacterColor);
return new StringTextRun(newlineText, p);
}
internal ReadOnlyMemory<char> GetPrecedingText(int textSourceCharacterIndexLimit)
{
try {
foreach (VisualLineElement element in VisualLine.Elements) {
if (textSourceCharacterIndexLimit > element.VisualColumn
&& textSourceCharacterIndexLimit <= element.VisualColumn + element.VisualLength) {
var span = element.GetPrecedingText(textSourceCharacterIndexLimit, this);
if (span.IsEmpty)
break;
int relativeOffset = textSourceCharacterIndexLimit - element.VisualColumn;
if (span.Length > relativeOffset)
throw new ArgumentException("The returned TextSpan is too long.", element.GetType().Name + ".GetPrecedingText");
return span;
}
}
return ReadOnlyMemory<char>.Empty;
} catch (Exception ex) {
Debug.Log(ex.ToString());
throw;
}
}
private string _cachedString;
private int _cachedStringOffset;
public StringSegment GetText(int offset, int length)
{
if (_cachedString != null) {
if (offset >= _cachedStringOffset && offset + length <= _cachedStringOffset + _cachedString.Length) {
return new StringSegment(_cachedString, offset - _cachedStringOffset, length);
}
}
_cachedStringOffset = offset;
return new StringSegment(_cachedString = Document.GetText(offset, length));
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 42f48d12e7fc440891c9b505fcebe808
timeCreated: 1710783075
@@ -0,0 +1,50 @@
// 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;
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// A VisualLinesInvalidException indicates that you accessed the <see cref="TextView.VisualLines"/> property
/// of the <see cref="TextView"/> while the visual lines were invalid.
/// </summary>
internal class VisualLinesInvalidException : Exception
{
/// <summary>
/// Creates a new VisualLinesInvalidException instance.
/// </summary>
internal VisualLinesInvalidException()
{
}
/// <summary>
/// Creates a new VisualLinesInvalidException instance.
/// </summary>
internal VisualLinesInvalidException(string message) : base(message)
{
}
/// <summary>
/// Creates a new VisualLinesInvalidException instance.
/// </summary>
internal VisualLinesInvalidException(string message, Exception innerException) : base(message, innerException)
{
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 17983278f10d4455a8b77556019ab3b1
timeCreated: 1710764034
@@ -0,0 +1,59 @@
// 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.
namespace Unity.CodeEditor.Rendering
{
/// <summary>
/// An enum that specifies the possible Y positions that can be returned by VisualLine.GetVisualPosition.
/// </summary>
internal enum VisualYPosition
{
/// <summary>
/// Returns the top of the TextLine.
/// </summary>
LineTop,
/// <summary>
/// Returns the top of the text.
/// If the line contains inline UI elements larger than the text, TextTop may be below LineTop.
/// For a line containing regular text (all in the editor's main font), this will be equal to LineTop.
/// </summary>
TextTop,
/// <summary>
/// Returns the bottom of the TextLine.
/// </summary>
LineBottom,
/// <summary>
/// The middle between LineTop and LineBottom.
/// </summary>
LineMiddle,
/// <summary>
/// Returns the bottom of the text.
/// If the line contains inline UI elements larger than the text, TextBottom might be above LineBottom.
/// For a line containing regular text (all in the editor's main font), this will be equal to LineBottom.
/// </summary>
TextBottom,
/// <summary>
/// The middle between TextTop and TextBottom.
/// </summary>
TextMiddle,
/// <summary>
/// Returns the baseline of the text.
/// </summary>
Baseline
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4075c9f563ed474ca5c3bb24a201259c
timeCreated: 1710764034