Search is not available for this dataset
id
stringlengths
1
8
text
stringlengths
72
9.81M
addition_count
int64
0
10k
commit_subject
stringlengths
0
3.7k
deletion_count
int64
0
8.43k
file_extension
stringlengths
0
32
lang
stringlengths
1
94
license
stringclasses
10 values
repo_name
stringlengths
9
59
10057350
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int foregroundColor); IBrush GetForegroundBrush(int foregroundColor); } public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { _colorMap = colorMap; Foreground = brushId; } public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) GetFontStyle(), return; } if (!_colorMap.Contains(Foreground)) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); } IColorMap _colorMap; <MSG> Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values <DFF> @@ -24,18 +24,28 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int foregroundColor); - IBrush GetForegroundBrush(int foregroundColor); + bool Contains(int color); + IBrush GetBrush(int color); } - public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) + int _foregroundBrushId; + int _backgroundBrushId; + int _fontStyle; + + public ForegroundTextTransformation( + IColorMap colorMap, + int startOffset, + int endOffset, + int foregroundBrushId, + int backgroundBrushId, + int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - Foreground = brushId; + _foregroundBrushId = foregroundBrushId; + _backgroundBrushId = backgroundBrushId; + _fontStyle = fontStyle; } - public int Foreground { get; set; } - public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) @@ -43,11 +53,6 @@ namespace AvaloniaEdit.TextMate return; } - if (!_colorMap.Contains(Foreground)) - { - return; - } - var formattedOffset = 0; var endOffset = line.EndOffset; @@ -61,7 +66,39 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, + _colorMap.GetBrush(_foregroundBrushId), + _colorMap.GetBrush(_backgroundBrushId), + GetFontStyle(), + GetFontWeight(), + IsUnderline()); + } + + FontStyle GetFontStyle() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return FontStyle.Italic; + + return FontStyle.Normal; + } + + FontWeight GetFontWeight() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return FontWeight.Bold; + + return FontWeight.Regular; + } + + bool IsUnderline() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + return true; + + return false; } IColorMap _colorMap;
49
Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values
12
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10057351
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int foregroundColor); IBrush GetForegroundBrush(int foregroundColor); } public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { _colorMap = colorMap; Foreground = brushId; } public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) GetFontStyle(), return; } if (!_colorMap.Contains(Foreground)) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); } IColorMap _colorMap; <MSG> Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values <DFF> @@ -24,18 +24,28 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int foregroundColor); - IBrush GetForegroundBrush(int foregroundColor); + bool Contains(int color); + IBrush GetBrush(int color); } - public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) + int _foregroundBrushId; + int _backgroundBrushId; + int _fontStyle; + + public ForegroundTextTransformation( + IColorMap colorMap, + int startOffset, + int endOffset, + int foregroundBrushId, + int backgroundBrushId, + int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - Foreground = brushId; + _foregroundBrushId = foregroundBrushId; + _backgroundBrushId = backgroundBrushId; + _fontStyle = fontStyle; } - public int Foreground { get; set; } - public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) @@ -43,11 +53,6 @@ namespace AvaloniaEdit.TextMate return; } - if (!_colorMap.Contains(Foreground)) - { - return; - } - var formattedOffset = 0; var endOffset = line.EndOffset; @@ -61,7 +66,39 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, + _colorMap.GetBrush(_foregroundBrushId), + _colorMap.GetBrush(_backgroundBrushId), + GetFontStyle(), + GetFontWeight(), + IsUnderline()); + } + + FontStyle GetFontStyle() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return FontStyle.Italic; + + return FontStyle.Normal; + } + + FontWeight GetFontWeight() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return FontWeight.Bold; + + return FontWeight.Regular; + } + + bool IsUnderline() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + return true; + + return false; } IColorMap _colorMap;
49
Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values
12
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10057352
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int foregroundColor); IBrush GetForegroundBrush(int foregroundColor); } public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { _colorMap = colorMap; Foreground = brushId; } public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) GetFontStyle(), return; } if (!_colorMap.Contains(Foreground)) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); } IColorMap _colorMap; <MSG> Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values <DFF> @@ -24,18 +24,28 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int foregroundColor); - IBrush GetForegroundBrush(int foregroundColor); + bool Contains(int color); + IBrush GetBrush(int color); } - public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) + int _foregroundBrushId; + int _backgroundBrushId; + int _fontStyle; + + public ForegroundTextTransformation( + IColorMap colorMap, + int startOffset, + int endOffset, + int foregroundBrushId, + int backgroundBrushId, + int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - Foreground = brushId; + _foregroundBrushId = foregroundBrushId; + _backgroundBrushId = backgroundBrushId; + _fontStyle = fontStyle; } - public int Foreground { get; set; } - public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) @@ -43,11 +53,6 @@ namespace AvaloniaEdit.TextMate return; } - if (!_colorMap.Contains(Foreground)) - { - return; - } - var formattedOffset = 0; var endOffset = line.EndOffset; @@ -61,7 +66,39 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, + _colorMap.GetBrush(_foregroundBrushId), + _colorMap.GetBrush(_backgroundBrushId), + GetFontStyle(), + GetFontWeight(), + IsUnderline()); + } + + FontStyle GetFontStyle() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return FontStyle.Italic; + + return FontStyle.Normal; + } + + FontWeight GetFontWeight() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return FontWeight.Bold; + + return FontWeight.Regular; + } + + bool IsUnderline() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + return true; + + return false; } IColorMap _colorMap;
49
Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values
12
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10057353
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int foregroundColor); IBrush GetForegroundBrush(int foregroundColor); } public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { _colorMap = colorMap; Foreground = brushId; } public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) GetFontStyle(), return; } if (!_colorMap.Contains(Foreground)) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); } IColorMap _colorMap; <MSG> Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values <DFF> @@ -24,18 +24,28 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int foregroundColor); - IBrush GetForegroundBrush(int foregroundColor); + bool Contains(int color); + IBrush GetBrush(int color); } - public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) + int _foregroundBrushId; + int _backgroundBrushId; + int _fontStyle; + + public ForegroundTextTransformation( + IColorMap colorMap, + int startOffset, + int endOffset, + int foregroundBrushId, + int backgroundBrushId, + int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - Foreground = brushId; + _foregroundBrushId = foregroundBrushId; + _backgroundBrushId = backgroundBrushId; + _fontStyle = fontStyle; } - public int Foreground { get; set; } - public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) @@ -43,11 +53,6 @@ namespace AvaloniaEdit.TextMate return; } - if (!_colorMap.Contains(Foreground)) - { - return; - } - var formattedOffset = 0; var endOffset = line.EndOffset; @@ -61,7 +66,39 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, + _colorMap.GetBrush(_foregroundBrushId), + _colorMap.GetBrush(_backgroundBrushId), + GetFontStyle(), + GetFontWeight(), + IsUnderline()); + } + + FontStyle GetFontStyle() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return FontStyle.Italic; + + return FontStyle.Normal; + } + + FontWeight GetFontWeight() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return FontWeight.Bold; + + return FontWeight.Regular; + } + + bool IsUnderline() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + return true; + + return false; } IColorMap _colorMap;
49
Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values
12
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10057354
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int foregroundColor); IBrush GetForegroundBrush(int foregroundColor); } public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { _colorMap = colorMap; Foreground = brushId; } public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) GetFontStyle(), return; } if (!_colorMap.Contains(Foreground)) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); } IColorMap _colorMap; <MSG> Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values <DFF> @@ -24,18 +24,28 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int foregroundColor); - IBrush GetForegroundBrush(int foregroundColor); + bool Contains(int color); + IBrush GetBrush(int color); } - public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) + int _foregroundBrushId; + int _backgroundBrushId; + int _fontStyle; + + public ForegroundTextTransformation( + IColorMap colorMap, + int startOffset, + int endOffset, + int foregroundBrushId, + int backgroundBrushId, + int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - Foreground = brushId; + _foregroundBrushId = foregroundBrushId; + _backgroundBrushId = backgroundBrushId; + _fontStyle = fontStyle; } - public int Foreground { get; set; } - public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) @@ -43,11 +53,6 @@ namespace AvaloniaEdit.TextMate return; } - if (!_colorMap.Contains(Foreground)) - { - return; - } - var formattedOffset = 0; var endOffset = line.EndOffset; @@ -61,7 +66,39 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, + _colorMap.GetBrush(_foregroundBrushId), + _colorMap.GetBrush(_backgroundBrushId), + GetFontStyle(), + GetFontWeight(), + IsUnderline()); + } + + FontStyle GetFontStyle() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return FontStyle.Italic; + + return FontStyle.Normal; + } + + FontWeight GetFontWeight() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return FontWeight.Bold; + + return FontWeight.Regular; + } + + bool IsUnderline() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + return true; + + return false; } IColorMap _colorMap;
49
Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values
12
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10057355
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int foregroundColor); IBrush GetForegroundBrush(int foregroundColor); } public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { _colorMap = colorMap; Foreground = brushId; } public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) GetFontStyle(), return; } if (!_colorMap.Contains(Foreground)) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); } IColorMap _colorMap; <MSG> Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values <DFF> @@ -24,18 +24,28 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int foregroundColor); - IBrush GetForegroundBrush(int foregroundColor); + bool Contains(int color); + IBrush GetBrush(int color); } - public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) + int _foregroundBrushId; + int _backgroundBrushId; + int _fontStyle; + + public ForegroundTextTransformation( + IColorMap colorMap, + int startOffset, + int endOffset, + int foregroundBrushId, + int backgroundBrushId, + int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - Foreground = brushId; + _foregroundBrushId = foregroundBrushId; + _backgroundBrushId = backgroundBrushId; + _fontStyle = fontStyle; } - public int Foreground { get; set; } - public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) @@ -43,11 +53,6 @@ namespace AvaloniaEdit.TextMate return; } - if (!_colorMap.Contains(Foreground)) - { - return; - } - var formattedOffset = 0; var endOffset = line.EndOffset; @@ -61,7 +66,39 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, + _colorMap.GetBrush(_foregroundBrushId), + _colorMap.GetBrush(_backgroundBrushId), + GetFontStyle(), + GetFontWeight(), + IsUnderline()); + } + + FontStyle GetFontStyle() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return FontStyle.Italic; + + return FontStyle.Normal; + } + + FontWeight GetFontWeight() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return FontWeight.Bold; + + return FontWeight.Regular; + } + + bool IsUnderline() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + return true; + + return false; } IColorMap _colorMap;
49
Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values
12
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10057356
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int foregroundColor); IBrush GetForegroundBrush(int foregroundColor); } public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { _colorMap = colorMap; Foreground = brushId; } public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) GetFontStyle(), return; } if (!_colorMap.Contains(Foreground)) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); } IColorMap _colorMap; <MSG> Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values <DFF> @@ -24,18 +24,28 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int foregroundColor); - IBrush GetForegroundBrush(int foregroundColor); + bool Contains(int color); + IBrush GetBrush(int color); } - public ForegroundTextTransformation(IColorMap colorMap, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) + int _foregroundBrushId; + int _backgroundBrushId; + int _fontStyle; + + public ForegroundTextTransformation( + IColorMap colorMap, + int startOffset, + int endOffset, + int foregroundBrushId, + int backgroundBrushId, + int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - Foreground = brushId; + _foregroundBrushId = foregroundBrushId; + _backgroundBrushId = backgroundBrushId; + _fontStyle = fontStyle; } - public int Foreground { get; set; } - public override void Transform(GenericLineTransformer transformer, DocumentLine line) { if (Length == 0) @@ -43,11 +53,6 @@ namespace AvaloniaEdit.TextMate return; } - if (!_colorMap.Contains(Foreground)) - { - return; - } - var formattedOffset = 0; var endOffset = line.EndOffset; @@ -61,7 +66,39 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetForegroundBrush(Foreground)); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, + _colorMap.GetBrush(_foregroundBrushId), + _colorMap.GetBrush(_backgroundBrushId), + GetFontStyle(), + GetFontWeight(), + IsUnderline()); + } + + FontStyle GetFontStyle() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return FontStyle.Italic; + + return FontStyle.Normal; + } + + FontWeight GetFontWeight() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return FontWeight.Bold; + + return FontWeight.Regular; + } + + bool IsUnderline() + { + if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + return true; + + return false; } IColorMap _colorMap;
49
Finally, calculate the backgroundBrush, the FontStyle and FontWeitgh based on the _backgroundBrushId and the fontStyle values
12
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10057357
<NME> GruntFile.js <BEF> module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), browserify: { build: { src: 'lib/index.js', src: [ 'component.json', 'package.json', 'lib/fruitmachine.js' ] }, standalone: '<%= pkg.name %>' } }, run: { test: { cmd: 'npm', args: [ 'test' ], } }, uglify: { build: { src: 'build/<%= pkg.name %>.js', dest: 'build/<%= pkg.name %>.min.js' } }, watch: { scripts: { files: ['lib/**/*.js'], tasks: ['browserify'] } }, instrument: { files: 'lib/**/*.js', options: { basePath: 'coverage/' } }, }); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-run'); // Default task. grunt.registerTask('default', ['browserify:build', 'uglify']); grunt.registerTask('test', ['browserify:test', 'run:test']); }; <MSG> Change version file <DFF> @@ -10,7 +10,7 @@ module.exports = function(grunt) { src: [ 'component.json', 'package.json', - 'lib/fruitmachine.js' + 'lib/index.js' ] },
1
Change version file
1
.js
js
mit
ftlabs/fruitmachine
10057358
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057359
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057360
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057361
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057362
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057363
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057364
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057365
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057366
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057367
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057368
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057369
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057370
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057371
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057372
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> </ItemGroup> </Project> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia again. <DFF> @@ -38,7 +38,7 @@ <PackageReference Include="System.Collections.Immutable" Version="1.3.1" /> <PackageReference Include="System.ValueTuple" Version="4.3.0" /> <PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" /> - <PackageReference Include="Avalonia" Version="0.5.1-build3351-alpha" /> + <PackageReference Include="Avalonia" Version="0.5.1-build3388-alpha" /> </ItemGroup> </Project> \ No newline at end of file
1
update avalonia again.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10057373
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057374
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057375
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057376
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057377
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057378
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057379
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057380
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057381
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057382
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057383
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057384
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057385
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057386
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057387
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.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> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; _element = element; } public override TextRunProperties Properties { get; } public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Removed unused using <DFF> @@ -18,7 +18,6 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Avalonia; using Avalonia.Media;
0
Removed unused using
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057388
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057389
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057390
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057391
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057392
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057393
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057394
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057395
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057396
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057397
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057398
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057399
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057400
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057401
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057402
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private void VerifyAccess() { Dispatcher.UIThread.VerifyAccess(); } /// <summary> public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (_lockObject) { if (ownerThread != null) { VerifyAccess(); } ownerThread = newOwner; } } private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Merge remote-tracking branch 'AvaloniaUI/master' into search <DFF> @@ -26,6 +26,7 @@ using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; +using System.Threading; namespace AvaloniaEdit.Document { @@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document return _rope.ToString(offset, length); } + private Thread ownerThread = Thread.CurrentThread; + private void VerifyAccess() { - Dispatcher.UIThread.VerifyAccess(); + if(Thread.CurrentThread != ownerThread) + { + throw new InvalidOperationException("Call from invalid thread."); + } } /// <summary>
7
Merge remote-tracking branch 'AvaloniaUI/master' into search
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057403
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057404
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057405
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057406
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057407
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057408
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057409
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057410
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057411
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057412
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057413
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057414
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057415
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057416
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057417
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.7</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update avalonia <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.7</AvaloniaVersion> + <AvaloniaVersion>0.9.9</AvaloniaVersion> </PropertyGroup> </Project>
1
update avalonia
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10057418
<NME> Ko.js <BEF> ADDFILE <MSG> korean language <DFF> @@ -0,0 +1,46 @@ +(function(jsGrid) { + + jsGrid.locales.ko = { + grid: { + noDataContent: "데이터가 없습니다.", + deleteConfirm: "데이터를 삭제 하겠습니까?", + pagerFormat: "페이지 : {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} / {pageCount}", + pagePrevText: "<", + pageNextText: ">", + pageFirstText: "<<", + pageLastText: ">>", + loadMessage: "잠시 기다려주세요...", + invalidMessage: "잘못된 데이터가 입력 되었습니다." + }, + + loadIndicator: { + message: "처리중..." + }, + + fields: { + control: { + searchModeButtonTooltip: "검색 모드", + insertModeButtonTooltip: "등록 모드", + editButtonTooltip: "수정", + deleteButtonTooltip: "삭제", + searchButtonTooltip: "검색", + clearFilterButtonTooltip: "초기화", + insertButtonTooltip: "등록", + updateButtonTooltip: "업데이트", + cancelEditButtonTooltip: "변경 취소" + } + }, + + validators: { + required: { message: "필수 입력" }, + rangeLength: { message: "입력된 값의 길이가 범위를 벗어났습니다." }, + minLength: { message: "입력된 값이 지정된 길이보다 짧습니다." }, + maxLength: { message: "입력된 값의 지정된 길이보다 깁니다." }, + pattern: { message: "입력된 값이 지정된 패턴과 일치하지 않습니다." }, + range: { message: "입력된 값이 범위를 벗어났습니다." }, + min: { message: "입력된 값이 지정된 범위보다 작습니다." }, + max: { message: "입력된 값이 지정된 범위보다 큽니다." } + } + }; + +}(jsGrid, jQuery));
46
korean language
0
.js
js
mit
tabalinas/jsgrid
10057419
<NME> Ko.js <BEF> ADDFILE <MSG> korean language <DFF> @@ -0,0 +1,46 @@ +(function(jsGrid) { + + jsGrid.locales.ko = { + grid: { + noDataContent: "데이터가 없습니다.", + deleteConfirm: "데이터를 삭제 하겠습니까?", + pagerFormat: "페이지 : {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} / {pageCount}", + pagePrevText: "<", + pageNextText: ">", + pageFirstText: "<<", + pageLastText: ">>", + loadMessage: "잠시 기다려주세요...", + invalidMessage: "잘못된 데이터가 입력 되었습니다." + }, + + loadIndicator: { + message: "처리중..." + }, + + fields: { + control: { + searchModeButtonTooltip: "검색 모드", + insertModeButtonTooltip: "등록 모드", + editButtonTooltip: "수정", + deleteButtonTooltip: "삭제", + searchButtonTooltip: "검색", + clearFilterButtonTooltip: "초기화", + insertButtonTooltip: "등록", + updateButtonTooltip: "업데이트", + cancelEditButtonTooltip: "변경 취소" + } + }, + + validators: { + required: { message: "필수 입력" }, + rangeLength: { message: "입력된 값의 길이가 범위를 벗어났습니다." }, + minLength: { message: "입력된 값이 지정된 길이보다 짧습니다." }, + maxLength: { message: "입력된 값의 지정된 길이보다 깁니다." }, + pattern: { message: "입력된 값이 지정된 패턴과 일치하지 않습니다." }, + range: { message: "입력된 값이 범위를 벗어났습니다." }, + min: { message: "입력된 값이 지정된 범위보다 작습니다." }, + max: { message: "입력된 값이 지정된 범위보다 큽니다." } + } + }; + +}(jsGrid, jQuery));
46
korean language
0
.js
js
mit
tabalinas/jsgrid
10057420
<NME> GruntFile.js <BEF> module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), browserify: { build: { src: 'lib/index.js', dest: 'build/<%= pkg.name %>.js' }, test: { src: 'coverage/lib/index.js', dest: 'coverage/build/<%= pkg.name %>.js' }, options: { standalone: '<%= pkg.name %>' } }, run: { test: { cmd: 'npm', args: [ 'test' ], } }, uglify: { build: { src: 'build/<%= pkg.name %>.js', dest: 'build/<%= pkg.name %>.min.js' } }, watch: { scripts: { files: ['lib/**/*.js'], tasks: ['browserify'] } watch: { scripts: { files: ['lib/*.js'], tasks: ['browserify'] } } }, }); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-run'); // Default task. grunt.registerTask('default', ['browserify:build', 'uglify']); grunt.registerTask('test', ['browserify:test', 'run:test']); }; <MSG> Deeper watch <DFF> @@ -40,7 +40,7 @@ module.exports = function(grunt) { watch: { scripts: { - files: ['lib/*.js'], + files: ['lib/**/*.js'], tasks: ['browserify'] } }
1
Deeper watch
1
.js
js
mit
ftlabs/fruitmachine
10057421
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057422
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057423
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057424
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057425
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057426
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057427
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057428
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057429
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057430
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057431
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057432
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057433
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057434
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057435
<NME> IServiceContainer.cs <BEF> using System; using System.Collections.Generic; namespace AvaloniaEdit.Utils { public interface IServiceContainer : IServiceProvider { void AddService(Type serviceType, object serviceInstance); void RemoveService(Type serviceType); } public static class ServiceExtensions { public static T GetService<T>(this IServiceProvider provider) where T : class { return provider.GetService(typeof(T)) as T; } public static void AddService<T>(this IServiceContainer container, T serviceInstance) { if (container == null) throw new ArgumentNullException(nameof(container)); container.AddService(typeof(T), serviceInstance); } public static void RemoveService<T>(this IServiceContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); container.RemoveService(typeof(T)); } } public class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public object GetService(Type serviceType) { _services.TryGetValue(serviceType, out var service); return service; } public void AddService(Type serviceType, object serviceInstance) { _services[serviceType] = serviceInstance; } public void RemoveService(Type serviceType) { _services.Remove(serviceType); } } } <MSG> Fixes for upcoming avalonia version. <DFF> @@ -32,7 +32,7 @@ namespace AvaloniaEdit.Utils } } - public class ServiceContainer : IServiceContainer + internal class ServiceContainer : IServiceContainer { private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
1
Fixes for upcoming avalonia version.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057436
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057437
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057438
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057439
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057440
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057441
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057442
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057443
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057444
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057445
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057446
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057447
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057448
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10057449
<NME> TextEditorOptions.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace AvaloniaEdit { /// <summary> /// A container for the text editor options. /// </summary> public class TextEditorOptions : INotifyPropertyChanged { #region ctor /// <summary> /// Initializes an empty instance of TextEditorOptions. /// </summary> public TextEditorOptions() { } /// <summary> /// Initializes a new instance of TextEditorOptions by copying all values /// from <paramref name="options"/> to the new instance. /// </summary> public TextEditorOptions(TextEditorOptions options) { // get all the fields in the class var fields = typeof(TextEditorOptions).GetRuntimeFields(); // copy each value over to 'this' foreach (FieldInfo fi in fields) { if (!fi.IsStatic) fi.SetValue(this, fi.GetValue(options)); } } #endregion #region PropertyChanged handling /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the changed property.</param> protected void OnPropertyChanged(string propertyName) { var args = new PropertyChangedEventArgs(propertyName); OnPropertyChanged(args); } /// <summary> /// Raises the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChanged?.Invoke(this, e); } #endregion #region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters private bool _showSpaces; /// <summary> /// Gets/Sets whether to show a visible glyph for spaces. The glyph displayed can be set via <see cref="ShowSpacesGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowSpaces { get { return _showSpaces; } set { if (_showSpaces != value) { _showSpaces = value; OnPropertyChanged(nameof(ShowSpaces)); } } } private string _showSpacesGlyph = "\u00B7"; /// <summary> /// Gets/Sets the char to show when ShowSpaces option is enabled /// </summary> /// <remarks>The default value is <c>·</c>.</remarks> [DefaultValue("\u00B7")] public virtual string ShowSpacesGlyph { get { return _showSpacesGlyph; } set { if (_showSpacesGlyph != value) { _showSpacesGlyph = value; OnPropertyChanged(nameof(ShowSpacesGlyph)); } } } private bool _showTabs; /// <summary> /// Gets/Sets whether to show a visible glyph for tab. The glyph displayed can be set via <see cref="ShowTabsGlyph" /> /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowTabs { get { return _showTabs; } set { if (_showTabs != value) { _showTabs = value; OnPropertyChanged(nameof(ShowTabs)); } } } private string _showTabsGlyph = "\u2192"; /// <summary> /// Gets/Sets the char to show when ShowTabs option is enabled /// </summary> /// <remarks>The default value is <c>→</c>.</remarks> [DefaultValue("\u2192")] public virtual string ShowTabsGlyph { get { return _showTabsGlyph; } set { if (_showTabsGlyph != value) { _showTabsGlyph = value; OnPropertyChanged(nameof(ShowTabsGlyph)); } } } private bool _showEndOfLine; /// <summary> /// Gets/Sets whether to show EOL char at the end of lines. The glyphs displayed can be set via <see cref="EndOfLineCRLFGlyph" />, <see cref="EndOfLineCRGlyph" /> and <see cref="EndOfLineLFGlyph" />. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ShowEndOfLine { get { return _showEndOfLine; } set { if (_showEndOfLine != value) { _showEndOfLine = value; OnPropertyChanged(nameof(ShowEndOfLine)); } } } private string _endOfLineCRLFGlyph = "¶"; /// <summary> /// Gets/Sets the char to show for CRLF (\r\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>¶</c>.</remarks> [DefaultValue("¶")] public virtual string EndOfLineCRLFGlyph { get { return _endOfLineCRLFGlyph; } set { if (_endOfLineCRLFGlyph != value) { _endOfLineCRLFGlyph = value; OnPropertyChanged(nameof(EndOfLineCRLFGlyph)); } } } private string _endOfLineCRGlyph = "\\r"; /// <summary> /// Gets/Sets the char to show for CR (\r) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\r</c>.</remarks> [DefaultValue("\\r")] public virtual string EndOfLineCRGlyph { get { return _endOfLineCRGlyph; } set { if (_endOfLineCRGlyph != value) { _endOfLineCRGlyph = value; OnPropertyChanged(nameof(EndOfLineCRGlyph)); } } } private string _endOfLineLFGlyph = "\\n"; /// <summary> /// Gets/Sets the char to show for LF (\n) when ShowEndOfLine option is enabled /// </summary> /// <remarks>The default value is <c>\n</c>.</remarks> [DefaultValue("\\n")] public virtual string EndOfLineLFGlyph { get { return _endOfLineLFGlyph; } set { if (_endOfLineLFGlyph != value) { _endOfLineLFGlyph = value; OnPropertyChanged(nameof(EndOfLineLFGlyph)); } } } private bool _showBoxForControlCharacters = true; /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool ShowBoxForControlCharacters { get { return _showBoxForControlCharacters; } set { if (_showBoxForControlCharacters != value) { _showBoxForControlCharacters = value; OnPropertyChanged(nameof(ShowBoxForControlCharacters)); } } } #endregion #region EnableHyperlinks private bool _enableHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableHyperlinks { get { return _enableHyperlinks; } set { if (_enableHyperlinks != value) { _enableHyperlinks = value; OnPropertyChanged(nameof(EnableHyperlinks)); } } } private bool _enableEmailHyperlinks = true; /// <summary> /// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool EnableEmailHyperlinks { get { return _enableEmailHyperlinks; } set { if (_enableEmailHyperlinks != value) { _enableEmailHyperlinks = value; OnPropertyChanged(nameof(EnableEmailHyperlinks)); } } } private bool _requireControlModifierForHyperlinkClick = true; /// <summary> /// Gets/Sets whether the user needs to press Control to click hyperlinks. /// The default value is true. /// </summary> /// <remarks>The default value is <c>true</c>.</remarks> [DefaultValue(true)] public virtual bool RequireControlModifierForHyperlinkClick { get { return _requireControlModifierForHyperlinkClick; } set { if (_requireControlModifierForHyperlinkClick != value) { _requireControlModifierForHyperlinkClick = value; } } private bool _allowScrollBelowDocument; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(false)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } /// <summary> /// Gets/Sets the width of one indentation unit. /// </summary> /// <remarks>The default value is 4.</remarks> [DefaultValue(4)] public virtual int IndentationSize { get => _indentationSize; set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, "value must be positive"); // sanity check; a too large value might cause a crash internally much later // (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts) if (value > 1000) throw new ArgumentOutOfRangeException(nameof(value), value, "indentation size is too large"); if (_indentationSize != value) { _indentationSize = value; OnPropertyChanged(nameof(IndentationSize)); OnPropertyChanged(nameof(IndentationString)); } } } private bool _convertTabsToSpaces; /// <summary> /// Gets/Sets whether to use spaces for indentation instead of tabs. /// </summary> /// <remarks>The default value is <c>false</c>.</remarks> [DefaultValue(false)] public virtual bool ConvertTabsToSpaces { get { return _convertTabsToSpaces; } set { if (_convertTabsToSpaces != value) { _convertTabsToSpaces = value; OnPropertyChanged(nameof(ConvertTabsToSpaces)); OnPropertyChanged(nameof(IndentationString)); } } } /// <summary> /// Gets the text used for indentation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public string IndentationString => GetIndentationString(1); /// <summary> /// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level. /// </summary> public virtual string GetIndentationString(int column) { if (column < 1) throw new ArgumentOutOfRangeException(nameof(column), column, "Value must be at least 1."); int indentationSize = IndentationSize; if (ConvertTabsToSpaces) { return new string(' ', indentationSize - ((column - 1) % indentationSize)); } else { return "\t"; } } #endregion private bool _cutCopyWholeLine = true; /// <summary> /// Gets/Sets whether copying without a selection copies the whole current line. /// </summary> [DefaultValue(true)] public virtual bool CutCopyWholeLine { get { return _cutCopyWholeLine; } set { if (_cutCopyWholeLine != value) { _cutCopyWholeLine = value; OnPropertyChanged(nameof(CutCopyWholeLine)); } } } private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is true; but it a good idea to set this property to true when using folding. /// </summary> [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; } set { if (_allowScrollBelowDocument != value) { _allowScrollBelowDocument = value; OnPropertyChanged(nameof(AllowScrollBelowDocument)); } } } private double _wordWrapIndentation; /// <summary> /// Gets/Sets the indentation used for all lines except the first when word-wrapping. /// The default value is 0. /// </summary> [DefaultValue(0.0)] public virtual double WordWrapIndentation { get => _wordWrapIndentation; set { if (double.IsNaN(value) || double.IsInfinity(value)) throw new ArgumentOutOfRangeException(nameof(value), value, "value must not be NaN/infinity"); if (value != _wordWrapIndentation) { _wordWrapIndentation = value; OnPropertyChanged(nameof(WordWrapIndentation)); } } } private bool _inheritWordWrapIndentation = true; /// <summary> /// Gets/Sets whether the indentation is inherited from the first line when word-wrapping. /// The default value is true. /// </summary> /// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks> [DefaultValue(true)] public virtual bool InheritWordWrapIndentation { get { return _inheritWordWrapIndentation; } set { if (value != _inheritWordWrapIndentation) { _inheritWordWrapIndentation = value; OnPropertyChanged(nameof(InheritWordWrapIndentation)); } } } private bool _enableRectangularSelection = true; /// <summary> /// Enables rectangular selection (press ALT and select a rectangle) /// </summary> [DefaultValue(true)] public bool EnableRectangularSelection { get { return _enableRectangularSelection; } set { if (_enableRectangularSelection != value) { _enableRectangularSelection = value; OnPropertyChanged(nameof(EnableRectangularSelection)); } } } private bool _enableTextDragDrop = true; /// <summary> /// Enable dragging text within the text area. /// </summary> [DefaultValue(true)] public bool EnableTextDragDrop { get { return _enableTextDragDrop; } set { if (_enableTextDragDrop != value) { _enableTextDragDrop = value; OnPropertyChanged(nameof(EnableTextDragDrop)); } } } private bool _enableVirtualSpace; /// <summary> /// Gets/Sets whether the user can set the caret behind the line ending /// (into "virtual space"). /// Note that virtual space is always used (independent from this setting) /// when doing rectangle selections. /// </summary> [DefaultValue(false)] public virtual bool EnableVirtualSpace { get { return _enableVirtualSpace; } set { if (_enableVirtualSpace != value) { _enableVirtualSpace = value; OnPropertyChanged(nameof(EnableVirtualSpace)); } } } private bool _enableImeSupport = true; /// <summary> /// Gets/Sets whether the support for Input Method Editors (IME) /// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled. /// </summary> [DefaultValue(true)] public virtual bool EnableImeSupport { get { return _enableImeSupport; } set { if (_enableImeSupport != value) { _enableImeSupport = value; OnPropertyChanged(nameof(EnableImeSupport)); } } } private bool _showColumnRulers; /// <summary> /// Gets/Sets whether the column rulers should be shown. /// </summary> [DefaultValue(false)] public virtual bool ShowColumnRulers { get { return _showColumnRulers; } set { if (_showColumnRulers != value) { _showColumnRulers = value; OnPropertyChanged(nameof(ShowColumnRulers)); } } } private IEnumerable<int> _columnRulerPositions = new List<int>() { 80 }; /// <summary> /// Gets/Sets the positions the column rulers should be shown. /// </summary> public virtual IEnumerable<int> ColumnRulerPositions { get { return _columnRulerPositions; } set { if (_columnRulerPositions != value) { _columnRulerPositions = value; OnPropertyChanged(nameof(ColumnRulerPositions)); } } } private bool _highlightCurrentLine; /// <summary> /// Gets/Sets if current line should be shown. /// </summary> [DefaultValue(false)] public virtual bool HighlightCurrentLine { get { return _highlightCurrentLine; } set { if (_highlightCurrentLine != value) { _highlightCurrentLine = value; OnPropertyChanged(nameof(HighlightCurrentLine)); } } } private bool _hideCursorWhileTyping = true; /// <summary> /// Gets/Sets if mouse cursor should be hidden while user is typing. /// </summary> [DefaultValue(true)] public bool HideCursorWhileTyping { get { return _hideCursorWhileTyping; } set { if (_hideCursorWhileTyping != value) { _hideCursorWhileTyping = value; OnPropertyChanged(nameof(HideCursorWhileTyping)); } } } private bool _allowToggleOverstrikeMode; /// <summary> /// Gets/Sets if the user is allowed to enable/disable overstrike mode. /// </summary> [DefaultValue(false)] public bool AllowToggleOverstrikeMode { get { return _allowToggleOverstrikeMode; } set { if (_allowToggleOverstrikeMode != value) { _allowToggleOverstrikeMode = value; OnPropertyChanged(nameof(AllowToggleOverstrikeMode)); } } } private bool _extendSelectionOnMouseUp = true; /// <summary> /// Gets/Sets if the mouse up event should extend the editor selection to the mouse position. /// </summary> [DefaultValue(true)] public bool ExtendSelectionOnMouseUp { get { return _extendSelectionOnMouseUp; } set { if (_extendSelectionOnMouseUp != value) { _extendSelectionOnMouseUp = value; OnPropertyChanged(nameof(ExtendSelectionOnMouseUp)); } } } } } <MSG> make allow scroll below end of document a little. <DFF> @@ -321,13 +321,13 @@ namespace AvaloniaEdit } } - private bool _allowScrollBelowDocument; + private bool _allowScrollBelowDocument = true; /// <summary> /// Gets/Sets whether the user can scroll below the bottom of the document. /// The default value is false; but it a good idea to set this property to true when using folding. /// </summary> - [DefaultValue(false)] + [DefaultValue(true)] public virtual bool AllowScrollBelowDocument { get { return _allowScrollBelowDocument; }
2
make allow scroll below end of document a little.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit