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
|
---|---|---|---|---|---|---|---|---|
10062050 | <NME> TextTransformation.cs
<BEF> using System;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public abstract class TextTransformation : TextSegment
{
public TextTransformation(object tag, int startOffset, int endOffset)
{
Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
startOffset, endOffset)
{
Foreground = foreground;
}
public IBrush Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
}
var formattedOffset = 0;
var endOffset = line.EndOffset;
if (StartOffset > line.Offset)
{
formattedOffset = StartOffset - line.Offset;
}
if (EndOffset < line.EndOffset)
{
endOffset = EndOffset;
}
endOffset = EndOffset;
}
transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
}
}
}
catch(Exception ex)
{
ExceptionHandler?.Invoke(ex);
}
}
AM.FontStyle GetFontStyle()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0)
return AM.FontStyle.Italic;
return AM.FontStyle.Normal;
}
AM.FontWeight GetFontWeight()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0)
return AM.FontWeight.Bold;
return AM.FontWeight.Regular;
}
bool IsUnderline()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0)
return true;
return false;
}
}
}
<MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
<DFF> @@ -1,34 +1,33 @@
using System;
+using System.Collections.Generic;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
-
public abstract class TextTransformation : TextSegment
{
- public TextTransformation(object tag, int startOffset, int endOffset)
+ public TextTransformation(int startOffset, int endOffset)
{
- Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
-
- public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
- public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
- startOffset, endOffset)
+ private readonly Dictionary<int, IBrush> _brushCache;
+
+ public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset)
{
- Foreground = foreground;
+ _brushCache = brushCache;
+ Foreground = brushId;
}
- public IBrush Foreground { get; set; }
+ public int Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
@@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate
endOffset = EndOffset;
}
- transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
+ transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]);
}
}
}
\ No newline at end of file
| 9 | Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support | 10 | .cs | TextMate/TextTransformation | mit | AvaloniaUI/AvaloniaEdit |
10062051 | <NME> TextTransformation.cs
<BEF> using System;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public abstract class TextTransformation : TextSegment
{
public TextTransformation(object tag, int startOffset, int endOffset)
{
Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
startOffset, endOffset)
{
Foreground = foreground;
}
public IBrush Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
}
var formattedOffset = 0;
var endOffset = line.EndOffset;
if (StartOffset > line.Offset)
{
formattedOffset = StartOffset - line.Offset;
}
if (EndOffset < line.EndOffset)
{
endOffset = EndOffset;
}
endOffset = EndOffset;
}
transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
}
}
}
catch(Exception ex)
{
ExceptionHandler?.Invoke(ex);
}
}
AM.FontStyle GetFontStyle()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0)
return AM.FontStyle.Italic;
return AM.FontStyle.Normal;
}
AM.FontWeight GetFontWeight()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0)
return AM.FontWeight.Bold;
return AM.FontWeight.Regular;
}
bool IsUnderline()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0)
return true;
return false;
}
}
}
<MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
<DFF> @@ -1,34 +1,33 @@
using System;
+using System.Collections.Generic;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
-
public abstract class TextTransformation : TextSegment
{
- public TextTransformation(object tag, int startOffset, int endOffset)
+ public TextTransformation(int startOffset, int endOffset)
{
- Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
-
- public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
- public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
- startOffset, endOffset)
+ private readonly Dictionary<int, IBrush> _brushCache;
+
+ public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset)
{
- Foreground = foreground;
+ _brushCache = brushCache;
+ Foreground = brushId;
}
- public IBrush Foreground { get; set; }
+ public int Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
@@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate
endOffset = EndOffset;
}
- transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
+ transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]);
}
}
}
\ No newline at end of file
| 9 | Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support | 10 | .cs | TextMate/TextTransformation | mit | AvaloniaUI/AvaloniaEdit |
10062052 | <NME> TextTransformation.cs
<BEF> using System;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public abstract class TextTransformation : TextSegment
{
public TextTransformation(object tag, int startOffset, int endOffset)
{
Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
startOffset, endOffset)
{
Foreground = foreground;
}
public IBrush Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
}
var formattedOffset = 0;
var endOffset = line.EndOffset;
if (StartOffset > line.Offset)
{
formattedOffset = StartOffset - line.Offset;
}
if (EndOffset < line.EndOffset)
{
endOffset = EndOffset;
}
endOffset = EndOffset;
}
transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
}
}
}
catch(Exception ex)
{
ExceptionHandler?.Invoke(ex);
}
}
AM.FontStyle GetFontStyle()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0)
return AM.FontStyle.Italic;
return AM.FontStyle.Normal;
}
AM.FontWeight GetFontWeight()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0)
return AM.FontWeight.Bold;
return AM.FontWeight.Regular;
}
bool IsUnderline()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0)
return true;
return false;
}
}
}
<MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
<DFF> @@ -1,34 +1,33 @@
using System;
+using System.Collections.Generic;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
-
public abstract class TextTransformation : TextSegment
{
- public TextTransformation(object tag, int startOffset, int endOffset)
+ public TextTransformation(int startOffset, int endOffset)
{
- Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
-
- public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
- public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
- startOffset, endOffset)
+ private readonly Dictionary<int, IBrush> _brushCache;
+
+ public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset)
{
- Foreground = foreground;
+ _brushCache = brushCache;
+ Foreground = brushId;
}
- public IBrush Foreground { get; set; }
+ public int Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
@@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate
endOffset = EndOffset;
}
- transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
+ transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]);
}
}
}
\ No newline at end of file
| 9 | Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support | 10 | .cs | TextMate/TextTransformation | mit | AvaloniaUI/AvaloniaEdit |
10062053 | <NME> TextTransformation.cs
<BEF> using System;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public abstract class TextTransformation : TextSegment
{
public TextTransformation(object tag, int startOffset, int endOffset)
{
Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
startOffset, endOffset)
{
Foreground = foreground;
}
public IBrush Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
}
var formattedOffset = 0;
var endOffset = line.EndOffset;
if (StartOffset > line.Offset)
{
formattedOffset = StartOffset - line.Offset;
}
if (EndOffset < line.EndOffset)
{
endOffset = EndOffset;
}
endOffset = EndOffset;
}
transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
}
}
}
catch(Exception ex)
{
ExceptionHandler?.Invoke(ex);
}
}
AM.FontStyle GetFontStyle()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0)
return AM.FontStyle.Italic;
return AM.FontStyle.Normal;
}
AM.FontWeight GetFontWeight()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0)
return AM.FontWeight.Bold;
return AM.FontWeight.Regular;
}
bool IsUnderline()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0)
return true;
return false;
}
}
}
<MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
<DFF> @@ -1,34 +1,33 @@
using System;
+using System.Collections.Generic;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
-
public abstract class TextTransformation : TextSegment
{
- public TextTransformation(object tag, int startOffset, int endOffset)
+ public TextTransformation(int startOffset, int endOffset)
{
- Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
-
- public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
- public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
- startOffset, endOffset)
+ private readonly Dictionary<int, IBrush> _brushCache;
+
+ public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset)
{
- Foreground = foreground;
+ _brushCache = brushCache;
+ Foreground = brushId;
}
- public IBrush Foreground { get; set; }
+ public int Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
@@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate
endOffset = EndOffset;
}
- transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
+ transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]);
}
}
}
\ No newline at end of file
| 9 | Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support | 10 | .cs | TextMate/TextTransformation | mit | AvaloniaUI/AvaloniaEdit |
10062054 | <NME> TextTransformation.cs
<BEF> using System;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public abstract class TextTransformation : TextSegment
{
public TextTransformation(object tag, int startOffset, int endOffset)
{
Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
startOffset, endOffset)
{
Foreground = foreground;
}
public IBrush Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
}
var formattedOffset = 0;
var endOffset = line.EndOffset;
if (StartOffset > line.Offset)
{
formattedOffset = StartOffset - line.Offset;
}
if (EndOffset < line.EndOffset)
{
endOffset = EndOffset;
}
endOffset = EndOffset;
}
transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
}
}
}
catch(Exception ex)
{
ExceptionHandler?.Invoke(ex);
}
}
AM.FontStyle GetFontStyle()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0)
return AM.FontStyle.Italic;
return AM.FontStyle.Normal;
}
AM.FontWeight GetFontWeight()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0)
return AM.FontWeight.Bold;
return AM.FontWeight.Regular;
}
bool IsUnderline()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0)
return true;
return false;
}
}
}
<MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
<DFF> @@ -1,34 +1,33 @@
using System;
+using System.Collections.Generic;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
-
public abstract class TextTransformation : TextSegment
{
- public TextTransformation(object tag, int startOffset, int endOffset)
+ public TextTransformation(int startOffset, int endOffset)
{
- Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
-
- public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
- public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
- startOffset, endOffset)
+ private readonly Dictionary<int, IBrush> _brushCache;
+
+ public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset)
{
- Foreground = foreground;
+ _brushCache = brushCache;
+ Foreground = brushId;
}
- public IBrush Foreground { get; set; }
+ public int Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
@@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate
endOffset = EndOffset;
}
- transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
+ transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]);
}
}
}
\ No newline at end of file
| 9 | Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support | 10 | .cs | TextMate/TextTransformation | mit | AvaloniaUI/AvaloniaEdit |
10062055 | <NME> TextTransformation.cs
<BEF> using System;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public abstract class TextTransformation : TextSegment
{
public TextTransformation(object tag, int startOffset, int endOffset)
{
Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
startOffset, endOffset)
{
Foreground = foreground;
}
public IBrush Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
}
var formattedOffset = 0;
var endOffset = line.EndOffset;
if (StartOffset > line.Offset)
{
formattedOffset = StartOffset - line.Offset;
}
if (EndOffset < line.EndOffset)
{
endOffset = EndOffset;
}
endOffset = EndOffset;
}
transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
}
}
}
catch(Exception ex)
{
ExceptionHandler?.Invoke(ex);
}
}
AM.FontStyle GetFontStyle()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0)
return AM.FontStyle.Italic;
return AM.FontStyle.Normal;
}
AM.FontWeight GetFontWeight()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0)
return AM.FontWeight.Bold;
return AM.FontWeight.Regular;
}
bool IsUnderline()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0)
return true;
return false;
}
}
}
<MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
<DFF> @@ -1,34 +1,33 @@
using System;
+using System.Collections.Generic;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
-
public abstract class TextTransformation : TextSegment
{
- public TextTransformation(object tag, int startOffset, int endOffset)
+ public TextTransformation(int startOffset, int endOffset)
{
- Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
-
- public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
- public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
- startOffset, endOffset)
+ private readonly Dictionary<int, IBrush> _brushCache;
+
+ public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset)
{
- Foreground = foreground;
+ _brushCache = brushCache;
+ Foreground = brushId;
}
- public IBrush Foreground { get; set; }
+ public int Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
@@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate
endOffset = EndOffset;
}
- transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
+ transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]);
}
}
}
\ No newline at end of file
| 9 | Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support | 10 | .cs | TextMate/TextTransformation | mit | AvaloniaUI/AvaloniaEdit |
10062056 | <NME> TextTransformation.cs
<BEF> using System;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public abstract class TextTransformation : TextSegment
{
public TextTransformation(object tag, int startOffset, int endOffset)
{
Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
startOffset, endOffset)
{
Foreground = foreground;
}
public IBrush Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
}
var formattedOffset = 0;
var endOffset = line.EndOffset;
if (StartOffset > line.Offset)
{
formattedOffset = StartOffset - line.Offset;
}
if (EndOffset < line.EndOffset)
{
endOffset = EndOffset;
}
endOffset = EndOffset;
}
transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
}
}
}
catch(Exception ex)
{
ExceptionHandler?.Invoke(ex);
}
}
AM.FontStyle GetFontStyle()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0)
return AM.FontStyle.Italic;
return AM.FontStyle.Normal;
}
AM.FontWeight GetFontWeight()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0)
return AM.FontWeight.Bold;
return AM.FontWeight.Regular;
}
bool IsUnderline()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0)
return true;
return false;
}
}
}
<MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
<DFF> @@ -1,34 +1,33 @@
using System;
+using System.Collections.Generic;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
-
public abstract class TextTransformation : TextSegment
{
- public TextTransformation(object tag, int startOffset, int endOffset)
+ public TextTransformation(int startOffset, int endOffset)
{
- Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
-
- public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
- public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
- startOffset, endOffset)
+ private readonly Dictionary<int, IBrush> _brushCache;
+
+ public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset)
{
- Foreground = foreground;
+ _brushCache = brushCache;
+ Foreground = brushId;
}
- public IBrush Foreground { get; set; }
+ public int Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
@@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate
endOffset = EndOffset;
}
- transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
+ transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]);
}
}
}
\ No newline at end of file
| 9 | Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support | 10 | .cs | TextMate/TextTransformation | mit | AvaloniaUI/AvaloniaEdit |
10062057 | <NME> TextTransformation.cs
<BEF> using System;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
public abstract class TextTransformation : TextSegment
{
public TextTransformation(object tag, int startOffset, int endOffset)
{
Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
startOffset, endOffset)
{
Foreground = foreground;
}
public IBrush Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
}
var formattedOffset = 0;
var endOffset = line.EndOffset;
if (StartOffset > line.Offset)
{
formattedOffset = StartOffset - line.Offset;
}
if (EndOffset < line.EndOffset)
{
endOffset = EndOffset;
}
endOffset = EndOffset;
}
transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
}
}
}
catch(Exception ex)
{
ExceptionHandler?.Invoke(ex);
}
}
AM.FontStyle GetFontStyle()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0)
return AM.FontStyle.Italic;
return AM.FontStyle.Normal;
}
AM.FontWeight GetFontWeight()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0)
return AM.FontWeight.Bold;
return AM.FontWeight.Regular;
}
bool IsUnderline()
{
if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet &&
(FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0)
return true;
return false;
}
}
}
<MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
<DFF> @@ -1,34 +1,33 @@
using System;
+using System.Collections.Generic;
using Avalonia.Media;
using AvaloniaEdit.Document;
using TextMateSharp.Model;
namespace AvaloniaEdit.TextMate
{
-
public abstract class TextTransformation : TextSegment
{
- public TextTransformation(object tag, int startOffset, int endOffset)
+ public TextTransformation(int startOffset, int endOffset)
{
- Tag = tag;
StartOffset = startOffset;
EndOffset = endOffset;
}
public abstract void Transform(GenericLineTransformer transformer, DocumentLine line);
-
- public object Tag { get; }
}
public class ForegroundTextTransformation : TextTransformation
{
- public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag,
- startOffset, endOffset)
+ private readonly Dictionary<int, IBrush> _brushCache;
+
+ public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset)
{
- Foreground = foreground;
+ _brushCache = brushCache;
+ Foreground = brushId;
}
- public IBrush Foreground { get; set; }
+ public int Foreground { get; set; }
public override void Transform(GenericLineTransformer transformer, DocumentLine line)
{
@@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate
endOffset = EndOffset;
}
- transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground);
+ transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]);
}
}
}
\ No newline at end of file
| 9 | Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support | 10 | .cs | TextMate/TextTransformation | mit | AvaloniaUI/AvaloniaEdit |
10062058 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062059 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062060 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062061 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062062 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062063 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062064 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062065 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062066 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062067 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062068 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062069 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062070 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062071 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062072 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</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> Merge pull request #195 from AvaloniaUI/patch-packageID
Correct PackageID
<DFF> @@ -4,6 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<Version>$(AvaloniaVersion)</Version>
+ <PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
<ItemGroup>
| 1 | Merge pull request #195 from AvaloniaUI/patch-packageID | 0 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10062073 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062074 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062075 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062076 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062077 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062078 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062079 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062080 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062081 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062082 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062083 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062084 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062085 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062086 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062087 | <NME> VisualLineLinkText.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Fixed hyperlink clicks and mouse handling
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Fixed hyperlink clicks and mouse handling | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062088 | <NME> README.md
<BEF> # Lumen Passport
[](https://travis-ci.org/dusterio/lumen-passport)
[](https://codeclimate.com/github/dusterio/lumen-passport/badges)
[](https://packagist.org/packages/dusterio/lumen-passport)
[](https://packagist.org/packages/dusterio/lumen-passport)
[](https://packagist.org/packages/dusterio/lumen-passport)
[](https://packagist.org/packages/dusterio/lumen-passport)
> Making Laravel Passport work with Lumen
## Introduction
It's a simple service provider that makes **Laravel Passport** work with **Lumen**.
## Installation
First install [Lumen Micro-Framework](https://github.com/laravel/lumen) if you don't have it yet.
Then install **Lumen Passport**:
```bash
composer require dusterio/lumen-passport
```
Or if you prefer, edit `composer.json` manually and run then `composer update`:
```json
{
"require": {
"dusterio/lumen-passport": "^0.3.5"
}
}
```
### Modify the bootstrap flow
We need to enable both **Laravel Passport** provider and **Lumen Passport** specific provider:
```php
/** @file bootstrap/app.php */
// Enable Facades
$app->withFacades();
// Enable Eloquent
$app->withEloquent();
// Enable auth middleware (shipped with Lumen)
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
// Register two service providers, Laravel Passport and Lumen adapter
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);
```
### Laravel Passport ^7.3.2 and newer
On 30 Jul 2019 [Laravel Passport 7.3.2](https://github.com/laravel/passport/releases/tag/v7.3.2) had a breaking change - new method introduced on Application class that exists in Laravel but not in Lumen. You could either lock in to an older version or swap the Application class like follows:
```php
/** @file bootstrap/app.php */
//$app = new Laravel\Lumen\Application(
// dirname(__DIR__)
//);
$app = new \Dusterio\LumenPassport\Lumen7Application(
dirname(__DIR__)
);
```
\* _Note: If you look inside this class - all it does is adding an extra method `configurationIsCached()` that always returns `false`._
### Migrate and install Laravel Passport
```bash
# Create new tables for Passport
php artisan migrate
# Install encryption keys and other stuff for Passport
php artisan passport:install
```
It will output the Personal access client ID and secret, and the Password grand client ID and secret.
];
```
## Todo
1. Add more unit and integration tests
## License
The MIT License (MIT)
Edit `config/auth.php` to suit your needs. A simple example:
```php
/** @file config/auth.php */
return [
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\Models\User::class
]
],
];
```
\* _Note: Lumen 7.x and older uses `\App\User::class`_
Load the config since Lumen doesn't load config files automatically:
```php
/** @file bootstrap/app.php */
$app->configure('auth');
```
### Registering Routes
Next, you should call the `LumenPassport::routes` method within the `boot` method of your application (one of your service providers). This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:
```php
/** @file app/Providers/AuthServiceProvider.php */
use Dusterio\LumenPassport\LumenPassport;
class AuthServiceProvider extends ServiceProvider
{
public function boot()
{
LumenPassport::routes($this->app);
/* rest of boot */
}
}
```
### User model
Make sure your user model uses **Laravel Passport**'s `HasApiTokens` trait.
```php
/** @file app/Models/User.php */
use Laravel\Passport\HasApiTokens;
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use HasApiTokens, Authenticatable, Authorizable, HasFactory;
/* rest of the model */
}
```
## Usage
You'll find all the documentation in [Laravel Passport Docs](https://laravel.com/docs/master/passport).
### Curl example with username and password authentication
First you have to [issue an access token](https://laravel.com/docs/master/passport#issuing-access-tokens) and then you can use it to authenticate your requests.
```bash
# Request
curl --location --request POST '{{APP_URL}}/oauth/token' \
--header 'Content-Type: application/json' \
--data-raw '{
"grant_type": "password",
"client_id": "{{CLIENT_ID}}",
"client_secret": "{{CLIENT_SECRET}}",
"username": "{{USER_EMAIL}}",
"password": "{{USER_PASSWORD}}",
"scope": "*"
}'
```
```json
{
"token_type": "Bearer",
"expires_in": 31536000,
"access_token": "******",
"refresh_token": "******"
}
```
And with the `access_token` you can request access to the routes that uses the Auth:Api Middleware provided by the **Lumen Passport**.
```php
/** @file routes/web.php */
$router->get('/ping', ['middleware' => 'auth', fn () => 'pong']);
```
```bash
# Request
curl --location --request GET '{{APP_URL}}/ping' \
--header 'Authorization: Bearer {{ACCESS_TOKEN}}'
```
```html
pong
```
### Installed routes
This package mounts the following routes after you call `routes()` method, all of them belongs to the namespace `\Laravel\Passport\Http\Controllers`:
Verb | Path | Controller | Action | Middleware
--- | --- | --- | --- | ---
POST | /oauth/token | AccessTokenController | issueToken | -
GET | /oauth/tokens | AuthorizedAccessTokenController | forUser | auth
DELETE | /oauth/tokens/{token_id} | AuthorizedAccessTokenController | destroy | auth
POST | /oauth/token/refresh | TransientTokenController | refresh | auth
GET | /oauth/clients | ClientController | forUser | auth
POST | /oauth/clients | ClientController | store | auth
PUT | /oauth/clients/{client_id} | ClientController | update | auth
DELETE | /oauth/clients/{client_id} | ClientController | destroy | auth
GET | /oauth/scopes | ScopeController | all | auth
GET | /oauth/personal-access-tokens | PersonalAccessTokenController | forUser | auth
POST | /oauth/personal-access-tokens | PersonalAccessTokenController | store | auth
DELETE | /oauth/personal-access-tokens/{token_id} | PersonalAccessTokenController | destroy | auth
\* _Note: some of the **Laravel Passport**'s routes had to 'go away' because they are web-related and rely on sessions (eg. authorise pages). Lumen is an API framework so only API-related routes are present._
## Extra features
There are a couple of extra features that aren't present in **Laravel Passport**
### Prefixing Routes
You can add that into an existing group, or add use this route registrar independently like so;
```php
/** @file app/Providers/AuthServiceProvider.php */
use Dusterio\LumenPassport\LumenPassport;
class AuthServiceProvider extends ServiceProvider
{
public function boot()
{
LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']);
/* rest of boot */
}
}
```
### Multiple tokens per client
Sometimes it's handy to allow multiple access tokens per password grant client. Eg. user logs in from several browsers
simultaneously. Currently **Laravel Passport** does not allow that.
```php
/** @file app/Providers/AuthServiceProvider.php */
use Dusterio\LumenPassport\LumenPassport;
class AuthServiceProvider extends ServiceProvider
{
public function boot()
{
LumenPassport::routes($this->app);
LumenPassport::allowMultipleTokens();
/* rest of boot */
}
}
```
### Different TTLs for different password clients
**Laravel Passport** allows to set one global TTL (time to live) for access tokens, but it may be useful sometimes to set different TTLs for different clients (eg. mobile users get more time than desktop users).
Simply do the following in your service provider:
```php
/** @file app/Providers/AuthServiceProvider.php */
use Carbon\Carbon;
use Dusterio\LumenPassport\LumenPassport;
class AuthServiceProvider extends ServiceProvider
{
public function boot()
{
LumenPassport::routes($this->app);
$client_id = '1';
LumenPassport::tokensExpireIn(Carbon::now()->addDays(14), $client_id);
/* rest of boot */
}
}
```
If you don't specify client Id, it will simply fall back to Laravel Passport implementation.
### Purge expired tokens
```bash
php artisan passport:purge
```
Simply run it to remove expired refresh tokens and their corresponding access tokens from the database.
## Error and issue resolution
Instead of opening a new issue, please see if someone has already had it and it has been resolved.
If you have found a bug or want to contribute to improving the package, please review the [Contributing guide](https://github.com/dusterio/lumen-passport/blob/master/CONTRIBUTING.md) and the [Code of Conduct](https://github.com/dusterio/lumen-passport/blob/master/CODE_OF_CONDUCT.md).
## Video tutorials
I've just started a educational YouTube channel [config.sys](https://www.youtube.com/channel/UCIvUJ1iVRjJP_xL0CD7cMpg) that will cover top IT trends in software development and DevOps.
Also I'm happy to announce my newest tool – [GrammarCI](https://www.grammarci.com/), an automated (as a part of CI/CD process) spelling and grammar checks for your code so that your users don't see your typos :)
## License
The MIT License (MIT)
Copyright (c) 2016 Denis Mysenko
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.
<MSG> r Readme update
<DFF> @@ -87,10 +87,6 @@ return [
];
```
-## Todo
-
-1. Add more unit and integration tests
-
## License
The MIT License (MIT)
| 0 | r Readme update | 4 | .md | md | mit | dusterio/lumen-passport |
10062089 | <NME> loadjs.js
<BEF> loadjs = (function () {
/**
* Global dependencies.
* @global {Object} document - DOM
*/
var devnull = function() {},
bundleIdCache = {},
bundleResultCache = {},
bundleCallbackQueue = {};
/**
* Subscribe to bundle load event.
* @param {string[]} bundleIds - Bundle ids
* @param {Function} callbackFn - The callback function
*/
function subscribe(bundleIds, callbackFn) {
// listify
bundleIds = bundleIds.push ? bundleIds : [bundleIds];
var depsNotFound = [],
i = bundleIds.length,
numWaiting = i,
fn,
bundleId,
r,
q;
// define callback function
fn = function (bundleId, pathsNotFound) {
if (pathsNotFound.length) depsNotFound.push(bundleId);
numWaiting--;
if (!numWaiting) callbackFn(depsNotFound);
};
// register callback
while (i--) {
bundleId = bundleIds[i];
// execute callback if in result cache
r = bundleResultCache[bundleId];
if (r) {
fn(bundleId, r);
continue;
}
// add to callback queue
q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];
q.push(fn);
}
}
/**
* Publish bundle load event.
* @param {string} bundleId - Bundle id
* @param {string[]} pathsNotFound - List of files not found
*/
function publish(bundleId, pathsNotFound) {
// exit if id isn't defined
if (!bundleId) return;
var q = bundleCallbackQueue[bundleId];
// cache result
bundleResultCache[bundleId] = pathsNotFound;
// exit if queue is empty
if (!q) return;
// empty callback queue
while (q.length) {
q[0](bundleId, pathsNotFound);
q.splice(0, 1);
}
}
/**
* Execute callbacks.
* @param {Object or Function} args - The callback args
* @param {string[]} depsNotFound - List of dependencies not found
*/
function executeCallbacks(args, depsNotFound) {
// accept function as argument
if (args.call) args = {success: args};
// success and error callbacks
if (depsNotFound.length) (args.error || devnull)(depsNotFound);
else (args.success || devnull)(args);
}
/**
* Load individual file.
* @param {string} path - The file path
* @param {Function} callbackFn - The callback function
*/
function loadFile(path, callbackFn, args, numTries) {
var doc = document,
async = args.async,
maxTries = (args.numRetries || 0) + 1,
beforeCallbackFn = args.before || devnull,
pathname = path.replace(/[\?|#].*$/, ''),
pathStripped = path.replace(/^(css|img)!/, ''),
isLegacyIECss,
e;
numTries = numTries || 0;
if (/(^css!|\.css$)/.test(pathname)) {
// css
e = doc.createElement('link');
e.rel = 'stylesheet';
e.href = pathStripped;
// tag IE9+
isLegacyIECss = 'hideFocus' in e;
// use preload in IE Edge (to detect load errors)
if (isLegacyIECss && e.relList) {
isLegacyIECss = 0;
e.rel = 'preload';
e.as = 'style';
}
} else if (/(^img!|\.(png|gif|jpg|svg|webp)$)/.test(pathname)) {
// image
e = doc.createElement('img');
e.src = pathStripped;
} else {
// javascript
e = doc.createElement('script');
e.src = path;
e.async = async === undefined ? true : async;
}
e.onload = e.onerror = e.onbeforeload = function (ev) {
if (arg1 && !arg1.call) bundleId = arg1;
// successFn, failFn
if (bundleId) successFn = arg2;
else successFn = arg1;
// failFn
if (bundleId) failFn = arg3;
else failFn = arg2;
// throw error if bundle is already defined
if (bundleId) {
// sheets objects created from load errors don't allow access to
// `cssText` (unless error is Code:18 SecurityError)
if (x.code != 18) result = 'e';
}
}
// handle retries in case of load failure
if (result == 'e') {
// increment counter
numTries += 1;
// exit function and try again
if (numTries < maxTries) {
return loadFile(path, callbackFn, args, numTries);
}
} else if (e.rel == 'preload' && e.as == 'style') {
// activate preloaded stylesheets
return e.rel = 'stylesheet'; // jshint ignore:line
}
// execute callback
callbackFn(path, result, ev.defaultPrevented);
};
// add to document (unless callback returns `false`)
if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e);
}
/**
* Load multiple files.
* @param {string[]} paths - The file paths
* @param {Function} callbackFn - The callback function
*/
function loadFiles(paths, callbackFn, args) {
// listify paths
paths = paths.push ? paths : [paths];
var numWaiting = paths.length,
x = numWaiting,
pathsNotFound = [],
fn,
i;
// define callback function
fn = function(path, result, defaultPrevented) {
// handle error
if (result == 'e') pathsNotFound.push(path);
// handle beforeload event. If defaultPrevented then that means the load
// will be blocked (ex. Ghostery/ABP on Safari)
if (result == 'b') {
if (defaultPrevented) pathsNotFound.push(path);
else return;
}
numWaiting--;
if (!numWaiting) callbackFn(pathsNotFound);
};
// load scripts
for (i=0; i < x; i++) loadFile(paths[i], fn, args);
}
/**
* Initiate script load and register bundle.
* @param {(string|string[])} paths - The file paths
* @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success
* callback or (3) object literal with success/error arguments, numRetries,
* etc.
* @param {(Function|Object)} [arg2] - The (1) success callback or (2) object
* literal with success/error arguments, numRetries, etc.
*/
function loadjs(paths, arg1, arg2) {
var bundleId,
args;
// bundleId (if string)
if (arg1 && arg1.trim) bundleId = arg1;
// args (default is {})
args = (bundleId ? arg2 : arg1) || {};
// throw error if bundle is already defined
if (bundleId) {
if (bundleId in bundleIdCache) {
throw "LoadJS";
} else {
bundleIdCache[bundleId] = true;
}
}
function loadFn(resolve, reject) {
loadFiles(paths, function (pathsNotFound) {
// execute callbacks
executeCallbacks(args, pathsNotFound);
// resolve Promise
if (resolve) {
executeCallbacks({success: resolve, error: reject}, pathsNotFound);
}
// publish bundle load event
publish(bundleId, pathsNotFound);
}, args);
}
if (args.returnPromise) return new Promise(loadFn);
else loadFn();
}
/**
* Execute callbacks when dependencies have been satisfied.
* @param {(string|string[])} deps - List of bundle ids
* @param {Object} args - success/error arguments
*/
loadjs.ready = function ready(deps, args) {
// subscribe to bundle load event
subscribe(deps, function (depsNotFound) {
// execute callbacks
executeCallbacks(args, depsNotFound);
});
return loadjs;
};
/**
* Manually satisfy bundle dependencies.
* @param {string} bundleId - The bundle id
*/
loadjs.done = function done(bundleId) {
publish(bundleId, []);
};
/**
* Reset loadjs dependencies statuses
*/
loadjs.reset = function reset() {
bundleIdCache = {};
bundleResultCache = {};
bundleCallbackQueue = {};
};
/**
* Determine if bundle has already been defined
* @param String} bundleId - The bundle id
*/
loadjs.isDefined = function isDefined(bundleId) {
return bundleId in bundleIdCache;
};
// export
return loadjs;
})();
<MSG> small fixes
<DFF> @@ -140,12 +140,8 @@ function loadjs(paths, arg1, arg2, arg3) {
if (arg1 && !arg1.call) bundleId = arg1;
// successFn, failFn
- if (bundleId) successFn = arg2;
- else successFn = arg1;
-
- // failFn
- if (bundleId) failFn = arg3;
- else failFn = arg2;
+ successFn = bundleId ? arg2 : arg1;
+ failFn = bundleId ? arg3 : arg2;
// throw error if bundle is already defined
if (bundleId) {
| 2 | small fixes | 6 | .js | js | mit | muicss/loadjs |
10062090 | <NME> loadjs.js
<BEF> loadjs = (function () {
/**
* Global dependencies.
* @global {Object} document - DOM
*/
var devnull = function() {},
bundleIdCache = {},
bundleResultCache = {},
bundleCallbackQueue = {};
/**
* Subscribe to bundle load event.
* @param {string[]} bundleIds - Bundle ids
* @param {Function} callbackFn - The callback function
*/
function subscribe(bundleIds, callbackFn) {
// listify
bundleIds = bundleIds.push ? bundleIds : [bundleIds];
var depsNotFound = [],
i = bundleIds.length,
numWaiting = i,
fn,
bundleId,
r,
q;
// define callback function
fn = function (bundleId, pathsNotFound) {
if (pathsNotFound.length) depsNotFound.push(bundleId);
numWaiting--;
if (!numWaiting) callbackFn(depsNotFound);
};
// register callback
while (i--) {
bundleId = bundleIds[i];
// execute callback if in result cache
r = bundleResultCache[bundleId];
if (r) {
fn(bundleId, r);
continue;
}
// add to callback queue
q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];
q.push(fn);
}
}
/**
* Publish bundle load event.
* @param {string} bundleId - Bundle id
* @param {string[]} pathsNotFound - List of files not found
*/
function publish(bundleId, pathsNotFound) {
// exit if id isn't defined
if (!bundleId) return;
var q = bundleCallbackQueue[bundleId];
// cache result
bundleResultCache[bundleId] = pathsNotFound;
// exit if queue is empty
if (!q) return;
// empty callback queue
while (q.length) {
q[0](bundleId, pathsNotFound);
q.splice(0, 1);
}
}
/**
* Execute callbacks.
* @param {Object or Function} args - The callback args
* @param {string[]} depsNotFound - List of dependencies not found
*/
function executeCallbacks(args, depsNotFound) {
// accept function as argument
if (args.call) args = {success: args};
// success and error callbacks
if (depsNotFound.length) (args.error || devnull)(depsNotFound);
else (args.success || devnull)(args);
}
/**
* Load individual file.
* @param {string} path - The file path
* @param {Function} callbackFn - The callback function
*/
function loadFile(path, callbackFn, args, numTries) {
var doc = document,
async = args.async,
maxTries = (args.numRetries || 0) + 1,
beforeCallbackFn = args.before || devnull,
pathname = path.replace(/[\?|#].*$/, ''),
pathStripped = path.replace(/^(css|img)!/, ''),
isLegacyIECss,
e;
numTries = numTries || 0;
if (/(^css!|\.css$)/.test(pathname)) {
// css
e = doc.createElement('link');
e.rel = 'stylesheet';
e.href = pathStripped;
// tag IE9+
isLegacyIECss = 'hideFocus' in e;
// use preload in IE Edge (to detect load errors)
if (isLegacyIECss && e.relList) {
isLegacyIECss = 0;
e.rel = 'preload';
e.as = 'style';
}
} else if (/(^img!|\.(png|gif|jpg|svg|webp)$)/.test(pathname)) {
// image
e = doc.createElement('img');
e.src = pathStripped;
} else {
// javascript
e = doc.createElement('script');
e.src = path;
e.async = async === undefined ? true : async;
}
e.onload = e.onerror = e.onbeforeload = function (ev) {
if (arg1 && !arg1.call) bundleId = arg1;
// successFn, failFn
if (bundleId) successFn = arg2;
else successFn = arg1;
// failFn
if (bundleId) failFn = arg3;
else failFn = arg2;
// throw error if bundle is already defined
if (bundleId) {
// sheets objects created from load errors don't allow access to
// `cssText` (unless error is Code:18 SecurityError)
if (x.code != 18) result = 'e';
}
}
// handle retries in case of load failure
if (result == 'e') {
// increment counter
numTries += 1;
// exit function and try again
if (numTries < maxTries) {
return loadFile(path, callbackFn, args, numTries);
}
} else if (e.rel == 'preload' && e.as == 'style') {
// activate preloaded stylesheets
return e.rel = 'stylesheet'; // jshint ignore:line
}
// execute callback
callbackFn(path, result, ev.defaultPrevented);
};
// add to document (unless callback returns `false`)
if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e);
}
/**
* Load multiple files.
* @param {string[]} paths - The file paths
* @param {Function} callbackFn - The callback function
*/
function loadFiles(paths, callbackFn, args) {
// listify paths
paths = paths.push ? paths : [paths];
var numWaiting = paths.length,
x = numWaiting,
pathsNotFound = [],
fn,
i;
// define callback function
fn = function(path, result, defaultPrevented) {
// handle error
if (result == 'e') pathsNotFound.push(path);
// handle beforeload event. If defaultPrevented then that means the load
// will be blocked (ex. Ghostery/ABP on Safari)
if (result == 'b') {
if (defaultPrevented) pathsNotFound.push(path);
else return;
}
numWaiting--;
if (!numWaiting) callbackFn(pathsNotFound);
};
// load scripts
for (i=0; i < x; i++) loadFile(paths[i], fn, args);
}
/**
* Initiate script load and register bundle.
* @param {(string|string[])} paths - The file paths
* @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success
* callback or (3) object literal with success/error arguments, numRetries,
* etc.
* @param {(Function|Object)} [arg2] - The (1) success callback or (2) object
* literal with success/error arguments, numRetries, etc.
*/
function loadjs(paths, arg1, arg2) {
var bundleId,
args;
// bundleId (if string)
if (arg1 && arg1.trim) bundleId = arg1;
// args (default is {})
args = (bundleId ? arg2 : arg1) || {};
// throw error if bundle is already defined
if (bundleId) {
if (bundleId in bundleIdCache) {
throw "LoadJS";
} else {
bundleIdCache[bundleId] = true;
}
}
function loadFn(resolve, reject) {
loadFiles(paths, function (pathsNotFound) {
// execute callbacks
executeCallbacks(args, pathsNotFound);
// resolve Promise
if (resolve) {
executeCallbacks({success: resolve, error: reject}, pathsNotFound);
}
// publish bundle load event
publish(bundleId, pathsNotFound);
}, args);
}
if (args.returnPromise) return new Promise(loadFn);
else loadFn();
}
/**
* Execute callbacks when dependencies have been satisfied.
* @param {(string|string[])} deps - List of bundle ids
* @param {Object} args - success/error arguments
*/
loadjs.ready = function ready(deps, args) {
// subscribe to bundle load event
subscribe(deps, function (depsNotFound) {
// execute callbacks
executeCallbacks(args, depsNotFound);
});
return loadjs;
};
/**
* Manually satisfy bundle dependencies.
* @param {string} bundleId - The bundle id
*/
loadjs.done = function done(bundleId) {
publish(bundleId, []);
};
/**
* Reset loadjs dependencies statuses
*/
loadjs.reset = function reset() {
bundleIdCache = {};
bundleResultCache = {};
bundleCallbackQueue = {};
};
/**
* Determine if bundle has already been defined
* @param String} bundleId - The bundle id
*/
loadjs.isDefined = function isDefined(bundleId) {
return bundleId in bundleIdCache;
};
// export
return loadjs;
})();
<MSG> small fixes
<DFF> @@ -140,12 +140,8 @@ function loadjs(paths, arg1, arg2, arg3) {
if (arg1 && !arg1.call) bundleId = arg1;
// successFn, failFn
- if (bundleId) successFn = arg2;
- else successFn = arg1;
-
- // failFn
- if (bundleId) failFn = arg3;
- else failFn = arg2;
+ successFn = bundleId ? arg2 : arg1;
+ failFn = bundleId ? arg3 : arg2;
// throw error if bundle is already defined
if (bundleId) {
| 2 | small fixes | 6 | .js | js | mit | muicss/loadjs |
10062091 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062092 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062093 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062094 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062095 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062096 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062097 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062098 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062099 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062100 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062101 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062102 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062103 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062104 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062105 | <NME> MainWindow.xaml.cs
<BEF> using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using AvaloniaEdit.CodeCompletion;
using AvaloniaEdit.Demo.Resources;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Folding;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using TextMateSharp.Grammars;
public class MainWindow : Window
{
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
{
private readonly TextEditor _textEditor;
private FoldingManager _foldingManager;
private readonly TextMate.TextMate.Installation _textMateInstallation;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
private Button _addControlButton;
private Button _clearControlButton;
private Button _changeThemeButton;
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
{
InitializeComponent();
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible;
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
_textEditor.ContextMenu = new ContextMenu
{
Items = new List<MenuItem>
{
new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) },
new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) },
new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) }
}
};
_textEditor.TextArea.Background = this.Background;
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.Options.ShowBoxForControlCharacters = true;
_textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 };
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
_textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_textEditor.TextArea.RightClickMovesCaret = true;
_addControlButton = this.FindControl<Button>("addControlBtn");
_addControlButton.Click += AddControlButton_Click;
_clearControlButton = this.FindControl<Button>("clearControlBtn");
_clearControlButton.Click += ClearControlButton_Click;
_textEditor.TextArea.TextView.Redraw();
}
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
_registryOptions = new RegistryOptions(
(ThemeName)_currentTheme);
_textMateInstallation = _textEditor.InstallTextMate(_registryOptions);
Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs");
_syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo");
_syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages();
_syntaxModeCombo.SelectedItem = csharpLanguage;
_syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged;
string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id);
_textEditor.Document = new TextDocument(
"// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine +
"// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine +
ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id));
_textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer());
_statusTextBlock = this.Find<TextBlock>("StatusText");
this.AddHandler(PointerWheelChangedEvent, (o, i) =>
{
if (i.KeyModifiers != KeyModifiers.Control) return;
if (i.Delta.Y > 0) _textEditor.FontSize++;
else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1;
}, RoutingStrategies.Bubble, true);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
_statusTextBlock.Text = string.Format("Line {0} Column {1}",
_textEditor.TextArea.Caret.Line,
_textEditor.TextArea.Caret.Column);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_textMateInstallation.Dispose();
}
private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RemoveUnderlineAndStrikethroughTransformer();
Language language = (Language)_syntaxModeCombo.SelectedItem;
if (_foldingManager != null)
{
_foldingManager.Clear();
FoldingManager.Uninstall(_foldingManager);
}
string scopeName = _registryOptions.GetScopeByLanguageId(language.Id);
_textMateInstallation.SetGrammar(null);
_textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName));
_textMateInstallation.SetGrammar(scopeName);
if (language.Id == "xml")
{
_foldingManager = FoldingManager.Install(_textEditor.TextArea);
var strategy = new XmlFoldingStrategy();
strategy.UpdateFoldings(_foldingManager, _textEditor.Document);
return;
}
}
private void RemoveUnderlineAndStrikethroughTransformer()
{
for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--)
{
if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer)
{
_textEditor.TextArea.TextView.LineTransformers.RemoveAt(i);
}
}
}
private void ChangeThemeButton_Click(object sender, RoutedEventArgs e)
{
_currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length;
_textMateInstallation.SetTheme(_registryOptions.LoadTheme(
(ThemeName)_currentTheme));
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
private void AddControlButton_Click(object sender, RoutedEventArgs e)
{
_generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default }));
_textEditor.TextArea.TextView.Redraw();
}
private void ClearControlButton_Click(object sender, RoutedEventArgs e)
{
textArea.Document.Replace(completionSegment, Text);
}
}
}
}
data.Add(new MyCompletionData("Item9"));
data.Add(new MyCompletionData("Item10"));
data.Add(new MyCompletionData("Item11"));
data.Add(new MyCompletionData("Item12"));
data.Add(new MyCompletionData("Item13"));
_completionWindow.Show();
}
else if (e.Text == "(")
{
_insightWindow = new OverloadInsightWindow(_textEditor.TextArea);
_insightWindow.Closed += (o, args) => _insightWindow = null;
_insightWindow.Provider = new MyOverloadProvider(new[]
{
("Method1(int, string)", "Method1 description"),
("Method2(int)", "Method2 description"),
("Method3(string)", "Method3 description"),
});
_insightWindow.Show();
}
}
class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer
{
protected override void ColorizeLine(DocumentLine line)
{
if (line.LineNumber == 2)
{
string lineText = this.CurrentContext.Document.GetText(line);
int indexOfUnderline = lineText.IndexOf("underline");
int indexOfStrikeThrough = lineText.IndexOf("strikethrough");
if (indexOfUnderline != -1)
{
ChangeLinePart(
line.Offset + indexOfUnderline,
line.Offset + indexOfUnderline + "underline".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
}
}
);
}
if (indexOfStrikeThrough != -1)
{
ChangeLinePart(
line.Offset + indexOfStrikeThrough,
line.Offset + indexOfStrikeThrough + "strikethrough".Length,
visualLine =>
{
if (visualLine.TextRunProperties.TextDecorations != null)
{
var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] };
visualLine.TextRunProperties.SetTextDecorations(textDecorations);
}
else
{
visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough);
}
}
);
}
}
}
}
private class MyOverloadProvider : IOverloadProvider
{
private readonly IList<(string header, string content)> _items;
private int _selectedIndex;
public MyOverloadProvider(IList<(string header, string content)> items)
{
_items = items;
SelectedIndex = 0;
}
public int SelectedIndex
{
get => _selectedIndex;
set
{
_selectedIndex = value;
OnPropertyChanged();
// ReSharper disable ExplicitCallerInfoArgument
OnPropertyChanged(nameof(CurrentHeader));
OnPropertyChanged(nameof(CurrentContent));
// ReSharper restore ExplicitCallerInfoArgument
}
}
public int Count => _items.Count;
public string CurrentIndexText => null;
public object CurrentHeader => _items[SelectedIndex].header;
public object CurrentContent => _items[SelectedIndex].content;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MyCompletionData : ICompletionData
{
public MyCompletionData(string text)
{
Text = text;
}
public IBitmap Image => null;
public string Text { get; }
// Use this property if you want to show a fancy UIElement in the list.
public object Content => Text;
public object Description => "Description for " + Text;
public double Priority { get; } = 0;
public void Complete(TextArea textArea, ISegment completionSegment,
EventArgs insertionRequestEventArgs)
{
textArea.Document.Replace(completionSegment, Text);
}
}
class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
{
public List<Pair> controls = new List<Pair>();
/// <summary>
/// Gets the first interested offset using binary search
/// </summary>
/// <returns>The first interested offset.</returns>
/// <param name="startOffset">Start offset.</param>
public override int GetFirstInterestedOffset(int startOffset)
{
int pos = controls.BinarySearch(new Pair(startOffset, null), this);
if (pos < 0)
pos = ~pos;
if (pos < controls.Count)
return controls[pos].Key;
else
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
int pos = controls.BinarySearch(new Pair(offset, null), this);
if (pos >= 0)
return new InlineObjectElement(0, controls[pos].Value);
else
return null;
}
int IComparer<Pair>.Compare(Pair x, Pair y)
{
return x.Key.CompareTo(y.Key);
}
}
}
}
<MSG> Restore completion demo
<DFF> @@ -20,42 +20,6 @@ namespace AvaloniaEdit.Demo
public class MainWindow : Window
{
-
- class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
- {
- public List<Pair> controls = new List<Pair>();
-
- /// <summary>
- /// Gets the first interested offset using binary search
- /// </summary>
- /// <returns>The first interested offset.</returns>
- /// <param name="startOffset">Start offset.</param>
- public override int GetFirstInterestedOffset(int startOffset)
- {
- int pos = controls.BinarySearch(new Pair(startOffset, null), this);
- if (pos < 0)
- pos = ~pos;
- if (pos < controls.Count)
- return controls[pos].Key;
- else
- return -1;
- }
-
- public override VisualLineElement ConstructElement(int offset)
- {
- int pos = controls.BinarySearch(new Pair(offset, null), this);
- if (pos >= 0)
- return new InlineObjectElement(0, controls[pos].Value);
- else
- return null;
- }
-
- int IComparer<Pair>.Compare(Pair x, Pair y)
- {
- return x.Key.CompareTo(y.Key);
- }
- }
-
private readonly TextEditor _textEditor;
private CompletionWindow _completionWindow;
private OverloadInsightWindow _insightWindow;
@@ -71,7 +35,7 @@ namespace AvaloniaEdit.Demo
_textEditor = this.FindControl<TextEditor>("Editor");
_textEditor.Background = Brushes.Transparent;
_textEditor.ShowLineNumbers = true;
- _textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
+ //_textEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
_textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;
_textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
_textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy();
@@ -109,8 +73,6 @@ namespace AvaloniaEdit.Demo
_textEditor.TextArea.TextView.Redraw();
}
-
-
void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e)
{
if (e.Text.Length > 0 && _completionWindow != null)
@@ -222,5 +184,40 @@ namespace AvaloniaEdit.Demo
textArea.Document.Replace(completionSegment, Text);
}
}
+
+ class ElementGenerator : VisualLineElementGenerator, IComparer<Pair>
+ {
+ public List<Pair> controls = new List<Pair>();
+
+ /// <summary>
+ /// Gets the first interested offset using binary search
+ /// </summary>
+ /// <returns>The first interested offset.</returns>
+ /// <param name="startOffset">Start offset.</param>
+ public override int GetFirstInterestedOffset(int startOffset)
+ {
+ int pos = controls.BinarySearch(new Pair(startOffset, null), this);
+ if (pos < 0)
+ pos = ~pos;
+ if (pos < controls.Count)
+ return controls[pos].Key;
+ else
+ return -1;
+ }
+
+ public override VisualLineElement ConstructElement(int offset)
+ {
+ int pos = controls.BinarySearch(new Pair(offset, null), this);
+ if (pos >= 0)
+ return new InlineObjectElement(0, controls[pos].Value);
+ else
+ return null;
+ }
+
+ int IComparer<Pair>.Compare(Pair x, Pair y)
+ {
+ return x.Key.CompareTo(y.Key);
+ }
+ }
}
}
| 36 | Restore completion demo | 39 | .cs | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10062106 | <NME> README.md
<BEF> # FruitMachine [](https://travis-ci.com/ftlabs/fruitmachine) [](https://coveralls.io/r/ftlabs/fruitmachine)
A lightweight component layout engine for client and server.
FruitMachine is designed to build rich interactive layouts from modular, reusable components. It's light and unopinionated so that it can be applied to almost any layout problem. FruitMachine is currently powering the [FT Web App](http://apps.ft.com/ftwebapp/).
```js
// Define a module
var Apple = fruitmachine.define({
name: 'apple',
template: function(){ return 'hello' }
});
// Create a module
var apple = new Apple();
// Render it
apple.render();
apple.el.outerHTML;
//=> <div class="apple">hello</div>
```
## Installation
```
$ npm install fruitmachine
```
## Documentation
- [Introduction](tree/master/docs/introduction.md)
- [Getting started](tree/master/docs/getting-started.md)
- [Defining modules](tree/master/docs/view-defining-modules.md)
- [View assembly](tree/master/docs/view-assembly.md)
- [Instantiation](tree/master/docs/view-instantiation.md)
- [Queries](tree/master/docs/view-queries.md)
- [Templates](tree/master/docs/view-templates.md)
- [Template markup](tree/master/docs/view-template-markup.md)
- [Rendering](tree/master/docs/view-rendering.md)
- [El](tree/master/docs/view-el.md)
- [Helpers](tree/master/docs/view-helpers.md)
- [DOM injection](tree/master/docs/view-injection.md)
- [Removing & destroying](tree/master/docs/view-removing-and-destroying.md)
- [Extending](tree/master/docs/view-extending.md)
## Why not Backbone?
- [Getting started](docs/getting-started.md)
- [Defining modules](docs/defining-modules.md)
- [Slots](docs/slots.md)
- [View assembly](docs/layout-assembly.md)
- [Instantiation](docs/module-instantiation.md)
- [Templates](docs/templates.md)
- [Template markup](docs/template-markup.md)
- [Rendering](docs/rendering.md)
- [DOM injection](docs/injection.md)
- [The module element](docs/module-el.md)
- [Queries](docs/queries.md)
- [Helpers](docs/module-helpers.md)
- [Removing & destroying](docs/removing-and-destroying.md)
- [Extending](docs/extending-modules.md)
- [Server-side rendering](docs/server-side-rendering.md)
- [API](docs/api.md)
- [Events](docs/events.md)
## Tests
#### With PhantomJS
```
$ npm install
$ npm test
```
#### Without PhantomJS
```
$ node_modules/.bin/buster-static
```
...then visit http://localhost:8282/ in browser
## Author
- **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage)
## Contributors
- **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage)
- **Matt Andrews** - [@matthew-andrews](http://github.com/matthew-andrews)
## License
Copyright (c) 2018 The Financial Times Limited
Licensed under the MIT license.
## Credits and collaboration
FruitMachine is largely unmaintained/finished. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request.
<MSG> Updated docs
<DFF> @@ -30,20 +30,20 @@ apple.el.outerHTML;
## Documentation
-- [Introduction](tree/master/docs/introduction.md)
-- [Getting started](tree/master/docs/getting-started.md)
-- [Defining modules](tree/master/docs/view-defining-modules.md)
-- [View assembly](tree/master/docs/view-assembly.md)
-- [Instantiation](tree/master/docs/view-instantiation.md)
-- [Queries](tree/master/docs/view-queries.md)
-- [Templates](tree/master/docs/view-templates.md)
-- [Template markup](tree/master/docs/view-template-markup.md)
-- [Rendering](tree/master/docs/view-rendering.md)
-- [El](tree/master/docs/view-el.md)
-- [Helpers](tree/master/docs/view-helpers.md)
-- [DOM injection](tree/master/docs/view-injection.md)
-- [Removing & destroying](tree/master/docs/view-removing-and-destroying.md)
-- [Extending](tree/master/docs/view-extending.md)
+- [Introduction](blob/master/docs/introduction.md)
+- [Getting started](blob/master/docs/getting-started.md)
+- [Defining modules](blob/master/docs/view-defining-modules.md)
+- [View assembly](blob/master/docs/view-assembly.md)
+- [Instantiation](blob/master/docs/view-instantiation.md)
+- [Queries](blob/master/docs/view-queries.md)
+- [Templates](blob/master/docs/view-templates.md)
+- [Template markup](blob/master/docs/view-template-markup.md)
+- [Rendering](blob/master/docs/view-rendering.md)
+- [El](blob/master/docs/view-el.md)
+- [Helpers](blob/master/docs/view-helpers.md)
+- [DOM injection](blob/master/docs/view-injection.md)
+- [Removing & destroying](blob/master/docs/view-removing-and-destroying.md)
+- [Extending](blob/master/docs/view-extending.md)
## Why not Backbone?
| 14 | Updated docs | 14 | .md | md | mit | ftlabs/fruitmachine |
10062107 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062108 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062109 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062110 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062111 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062112 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062113 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062114 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062115 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062116 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062117 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062118 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062119 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062120 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062121 | <NME> HighlightingColor.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.Globalization;
using System.Text;
using Avalonia.Media;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
private string _name;
private FontFamily _fontFamily;
private int? _fontSize;
private FontWeight? _fontWeight;
private FontStyle? _fontStyle;
private bool? _underline;
private bool? _strikethrough;
private HighlightingBrush _foreground;
private HighlightingBrush _background;
/// <summary>
/// Gets/Sets the name of the color.
/// </summary>
public string Name
{
get => _name;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_name = value;
}
}
/// <summary>
/// Gets/sets the font family. Null if the highlighting color does not change the font style.
/// </summary>
public FontFamily FontFamily
{
get
{
return _fontFamily;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontFamily = value;
}
}
/// <summary>
/// Gets/sets the font size. Null if the highlighting color does not change the font style.
/// </summary>
public int? FontSize
{
get
{
return _fontSize;
}
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontSize = value;
}
}
/// <summary>
/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
/// </summary>
public FontWeight? FontWeight
{
get => _fontWeight;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontWeight = value;
}
}
/// <summary>
/// Gets/sets the font style. Null if the highlighting color does not change the font style.
/// </summary>
public FontStyle? FontStyle
{
get => _fontStyle;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_fontStyle = value;
}
}
/// <summary>
/// Gets/sets the underline flag. Null if the underline status does not change the font style.
/// </summary>
public bool? Underline
{
get => _underline;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_underline = value;
}
}
/// <summary>
/// Gets/sets the strikethrough flag
/// </summary>
public bool? Strikethrough
{
get => _strikethrough;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_strikethrough = value;
}
}
/// <summary>
/// Gets/sets the foreground color applied by the highlighting.
/// </summary>
public HighlightingBrush Foreground
{
get => _foreground;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_foreground = value;
}
}
/// <summary>
/// Gets/sets the background color applied by the highlighting.
/// </summary>
public HighlightingBrush Background
{
get => _background;
set
{
if (IsFrozen)
throw new InvalidOperationException();
_background = value;
}
}
///// <summary>
///// Serializes this HighlightingColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
//}
/// <summary>
/// Gets CSS code for the color.
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
var b = new StringBuilder();
var c = Foreground?.GetColor(null);
return c;
}
object ICloneable.Clone()
{
return Clone();
}
b.Append(FontFamily.Name.ToLowerInvariant());
b.Append("; ");
}
if (FontSize != null)
{
b.Append("font-size: ");
b.Append(FontSize.Value.ToString());
b.Append("; ");
}
if (FontWeight != null)
{
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null)
{
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null)
{
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null)
{
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
/// <inheritdoc/>
public override string ToString()
{
return "[" + GetType().Name + " " + (string.IsNullOrEmpty(Name) ? ToCss() : Name) + "]";
}
/// <summary>
/// Prevent further changes to this highlighting color.
/// </summary>
public virtual void Freeze()
{
IsFrozen = true;
}
/// <summary>
/// Gets whether this HighlightingColor instance is frozen.
/// </summary>
public bool IsFrozen { get; private set; }
/// <summary>
/// Clones this highlighting color.
/// If this color is frozen, the clone will be unfrozen.
/// </summary>
public virtual HighlightingColor Clone()
{
var c = (HighlightingColor)MemberwiseClone();
c.IsFrozen = false;
return c;
}
object ICloneable.Clone()
{
return Clone();
}
/// <inheritdoc/>
public sealed override bool Equals(object obj)
{
return Equals(obj as HighlightingColor);
}
/// <inheritdoc/>
public virtual bool Equals(HighlightingColor other)
{
if (other == null)
return false;
return _name == other._name && _fontWeight == other._fontWeight
&& _fontStyle == other._fontStyle && _underline == other._underline && this._strikethrough == other._strikethrough
&& Equals(_foreground, other._foreground) && Equals(_background, other._background)
&& Equals(_fontFamily, other._fontFamily) && Equals(_fontSize, other._fontSize);
}
/// <inheritdoc/>
[SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
public override int GetHashCode()
{
var hashCode = 0;
unchecked
{
if (_name != null)
hashCode += 1000000007 * _name.GetHashCode();
hashCode += 1000000009 * _fontWeight.GetHashCode();
hashCode += 1000000021 * _fontStyle.GetHashCode();
if (_foreground != null)
hashCode += 1000000033 * _foreground.GetHashCode();
if (_background != null)
hashCode += 1000000087 * _background.GetHashCode();
if (_fontFamily != null)
hashCode += 1000000123 * _fontFamily.GetHashCode();
if (_fontSize != null)
hashCode += 1000000167 * _fontSize.GetHashCode();
}
return hashCode;
}
/// <summary>
/// Overwrites the properties in this HighlightingColor with those from the given color;
/// but maintains the current values where the properties of the given color return <c>null</c>.
/// </summary>
public void MergeWith(HighlightingColor color)
{
FreezableHelper.ThrowIfFrozen(this);
if (color._fontFamily != null)
_fontFamily = color._fontFamily;
if (color._fontSize != null)
_fontSize = color._fontSize;
if (color._fontWeight != null)
_fontWeight = color._fontWeight;
if (color._fontStyle != null)
_fontStyle = color._fontStyle;
if (color._foreground != null)
_foreground = color._foreground;
if (color._background != null)
_background = color._background;
if (color._underline != null)
_underline = color._underline;
if (color._strikethrough != null)
this._strikethrough = color._strikethrough;
}
internal bool IsEmptyForMerge => _fontWeight == null && _fontStyle == null && _underline == null
&& _strikethrough == null && _foreground == null && _background == null
&& _fontFamily == null && _fontSize == null;
}
}
<MSG> Fixed build and updated avalonia
<DFF> @@ -28,7 +28,7 @@ namespace AvaloniaEdit.Highlighting
/// <summary>
/// A highlighting color is a set of font properties and foreground and background color.
/// </summary>
- public class HighlightingColor : IFreezable, ICloneable, IEquatable<HighlightingColor>
+ public class HighlightingColor : IFreezable, AvaloniaEdit.Utils.ICloneable, IEquatable<HighlightingColor>
{
internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
@@ -207,7 +207,7 @@ namespace AvaloniaEdit.Highlighting
return c;
}
- object ICloneable.Clone()
+ object AvaloniaEdit.Utils.ICloneable.Clone()
{
return Clone();
}
| 2 | Fixed build and updated avalonia | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062122 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062123 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062124 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062125 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062126 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062127 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062128 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062129 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062130 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062131 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062132 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062133 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062134 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062135 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062136 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.11</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
</PropertyGroup>
</Project>
<MSG> bump version
<DFF> @@ -2,7 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.10.11</AvaloniaVersion>
+ <AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.21</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
</PropertyGroup>
| 1 | bump version | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10062137 | <NME> README.md
<BEF> # Lumen Passport
[](https://travis-ci.org/dusterio/lumen-passport)
[](https://codeclimate.com/github/dusterio/lumen-passport/badges)
[](https://packagist.org/packages/dusterio/lumen-passport)
[](https://packagist.org/packages/dusterio/lumen-passport)
[](https://packagist.org/packages/dusterio/lumen-passport)
[](https://packagist.org/packages/dusterio/lumen-passport)
> Making Laravel Passport work with Lumen
## Introduction
It's a simple service provider that makes **Laravel Passport** work with **Lumen**.
## Installation
First install [Lumen Micro-Framework](https://github.com/laravel/lumen) if you don't have it yet.
Then install **Lumen Passport**:
```bash
composer require dusterio/lumen-passport
```
Or if you prefer, edit `composer.json` manually and run then `composer update`:
```json
{
"require": {
"dusterio/lumen-passport": "^0.3.5"
}
}
```
### Modify the bootstrap flow
We need to enable both **Laravel Passport** provider and **Lumen Passport** specific provider:
```php
/** @file bootstrap/app.php */
// Enable Facades
$app->withFacades();
// Enable Eloquent
$app->withEloquent();
// Enable auth middleware (shipped with Lumen)
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
// Register two service providers, Laravel Passport and Lumen adapter
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);
```
### Laravel Passport ^7.3.2 and newer
On 30 Jul 2019 [Laravel Passport 7.3.2](https://github.com/laravel/passport/releases/tag/v7.3.2) had a breaking change - new method introduced on Application class that exists in Laravel but not in Lumen. You could either lock in to an older version or swap the Application class like follows:
```php
/** @file bootstrap/app.php */
//$app = new Laravel\Lumen\Application(
// dirname(__DIR__)
//);
$app = new \Dusterio\LumenPassport\Lumen7Application(
dirname(__DIR__)
);
```
\* _Note: If you look inside this class - all it does is adding an extra method `configurationIsCached()` that always returns `false`._
### Migrate and install Laravel Passport
```bash
# Create new tables for Passport
php artisan migrate
# Install encryption keys and other stuff for Passport
php artisan passport:install
```
It will output the Personal access client ID and secret, and the Password grand client ID and secret.
\* _Note: Save the secrets in a safe place, you'll need them later to request the access tokens._
## Configuration
### Configure Authentication
Edit `config/auth.php` to suit your needs. A simple example:
```php
/** @file config/auth.php */
return [
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\Models\User::class
]
],
];
```
\* _Note: Lumen 7.x and older uses `\App\User::class`_
Load the config since Lumen doesn't load config files automatically:
```php
/** @file bootstrap/app.php */
$app->configure('auth');
```
### Registering Routes
Next, you should call the `LumenPassport::routes` method within the `boot` method of your application (one of your service providers). This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:
```php
/** @file app/Providers/AuthServiceProvider.php */
use Dusterio\LumenPassport\LumenPassport;
class AuthServiceProvider extends ServiceProvider
{
public function boot()
{
LumenPassport::routes($this->app);
/* rest of boot */
}
}
```
### User model
Make sure your user model uses **Laravel Passport**'s `HasApiTokens` trait.
```php
/** @file app/Models/User.php */
use Laravel\Passport\HasApiTokens;
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use HasApiTokens, Authenticatable, Authorizable, HasFactory;
/* rest of the model */
}
```
## Usage
You'll find all the documentation in [Laravel Passport Docs](https://laravel.com/docs/master/passport).
### Curl example with username and password authentication
First you have to [issue an access token](https://laravel.com/docs/master/passport#issuing-access-tokens) and then you can use it to authenticate your requests.
```bash
# Request
curl --location --request POST '{{APP_URL}}/oauth/token' \
--header 'Content-Type: application/json' \
--data-raw '{
"grant_type": "password",
"client_id": "{{CLIENT_ID}}",
"client_secret": "{{CLIENT_SECRET}}",
"username": "{{USER_EMAIL}}",
"password": "{{USER_PASSWORD}}",
"scope": "*"
}'
```
```json
{
"token_type": "Bearer",
"expires_in": 31536000,
"access_token": "******",
"refresh_token": "******"
}
```
And with the `access_token` you can request access to the routes that uses the Auth:Api Middleware provided by the **Lumen Passport**.
```php
/** @file routes/web.php */
$router->get('/ping', ['middleware' => 'auth', fn () => 'pong']);
```
```bash
# Request
curl --location --request GET '{{APP_URL}}/ping' \
--header 'Authorization: Bearer {{ACCESS_TOKEN}}'
```
```html
pong
```
### Installed routes
This package mounts the following routes after you call `routes()` method, all of them belongs to the namespace `\Laravel\Passport\Http\Controllers`:
Verb | Path | Controller | Action | Middleware
--- | --- | --- | --- | ---
POST | /oauth/token | AccessTokenController | issueToken | -
GET | /oauth/tokens | AuthorizedAccessTokenController | forUser | auth
DELETE | /oauth/tokens/{token_id} | AuthorizedAccessTokenController | destroy | auth
POST | /oauth/token/refresh | TransientTokenController | refresh | auth
GET | /oauth/clients | ClientController | forUser | auth
POST | /oauth/clients | ClientController | store | auth
PUT | /oauth/clients/{client_id} | ClientController | update | auth
I've just started a educational YouTube channel that will cover top IT trends in software development and DevOps: [config.sys](https://www.youtube.com/channel/UCIvUJ1iVRjJP_xL0CD7cMpg)
## License
The MIT License (MIT)
## Extra features
There are a couple of extra features that aren't present in **Laravel Passport**
### Prefixing Routes
You can add that into an existing group, or add use this route registrar independently like so;
```php
/** @file app/Providers/AuthServiceProvider.php */
use Dusterio\LumenPassport\LumenPassport;
class AuthServiceProvider extends ServiceProvider
{
public function boot()
{
LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']);
/* rest of boot */
}
}
```
### Multiple tokens per client
Sometimes it's handy to allow multiple access tokens per password grant client. Eg. user logs in from several browsers
simultaneously. Currently **Laravel Passport** does not allow that.
```php
/** @file app/Providers/AuthServiceProvider.php */
use Dusterio\LumenPassport\LumenPassport;
class AuthServiceProvider extends ServiceProvider
{
public function boot()
{
LumenPassport::routes($this->app);
LumenPassport::allowMultipleTokens();
/* rest of boot */
}
}
```
### Different TTLs for different password clients
**Laravel Passport** allows to set one global TTL (time to live) for access tokens, but it may be useful sometimes to set different TTLs for different clients (eg. mobile users get more time than desktop users).
Simply do the following in your service provider:
```php
/** @file app/Providers/AuthServiceProvider.php */
use Carbon\Carbon;
use Dusterio\LumenPassport\LumenPassport;
class AuthServiceProvider extends ServiceProvider
{
public function boot()
{
LumenPassport::routes($this->app);
$client_id = '1';
LumenPassport::tokensExpireIn(Carbon::now()->addDays(14), $client_id);
/* rest of boot */
}
}
```
If you don't specify client Id, it will simply fall back to Laravel Passport implementation.
### Purge expired tokens
```bash
php artisan passport:purge
```
Simply run it to remove expired refresh tokens and their corresponding access tokens from the database.
## Error and issue resolution
Instead of opening a new issue, please see if someone has already had it and it has been resolved.
If you have found a bug or want to contribute to improving the package, please review the [Contributing guide](https://github.com/dusterio/lumen-passport/blob/master/CONTRIBUTING.md) and the [Code of Conduct](https://github.com/dusterio/lumen-passport/blob/master/CODE_OF_CONDUCT.md).
## Video tutorials
I've just started a educational YouTube channel [config.sys](https://www.youtube.com/channel/UCIvUJ1iVRjJP_xL0CD7cMpg) that will cover top IT trends in software development and DevOps.
Also I'm happy to announce my newest tool – [GrammarCI](https://www.grammarci.com/), an automated (as a part of CI/CD process) spelling and grammar checks for your code so that your users don't see your typos :)
## License
The MIT License (MIT)
Copyright (c) 2016 Denis Mysenko
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.
<MSG> Update README.md
<DFF> @@ -220,6 +220,8 @@ RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
I've just started a educational YouTube channel that will cover top IT trends in software development and DevOps: [config.sys](https://www.youtube.com/channel/UCIvUJ1iVRjJP_xL0CD7cMpg)
+Also I'm happy to announce my newest tool – [GrammarCI](https://www.grammarci.com/), an automated (as a part of CI/CD process) spelling and grammar checks for your code so that your users don't see your typos :)
+
## License
The MIT License (MIT)
| 2 | Update README.md | 0 | .md | md | mit | dusterio/lumen-passport |
10062138 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
}
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> invalidate margins on scroll.
<DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
+
+ foreach(var margin in LeftMargins)
+ {
+ margin.InvalidateVisual();
+ }
}
}
| 5 | invalidate margins on scroll. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062139 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
}
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> invalidate margins on scroll.
<DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
+
+ foreach(var margin in LeftMargins)
+ {
+ margin.InvalidateVisual();
+ }
}
}
| 5 | invalidate margins on scroll. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062140 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
}
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> invalidate margins on scroll.
<DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
+
+ foreach(var margin in LeftMargins)
+ {
+ margin.InvalidateVisual();
+ }
}
}
| 5 | invalidate margins on scroll. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062141 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
}
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> invalidate margins on scroll.
<DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
+
+ foreach(var margin in LeftMargins)
+ {
+ margin.InvalidateVisual();
+ }
}
}
| 5 | invalidate margins on scroll. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062142 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
}
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> invalidate margins on scroll.
<DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
+
+ foreach(var margin in LeftMargins)
+ {
+ margin.InvalidateVisual();
+ }
}
}
| 5 | invalidate margins on scroll. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062143 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
}
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> invalidate margins on scroll.
<DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
+
+ foreach(var margin in LeftMargins)
+ {
+ margin.InvalidateVisual();
+ }
}
}
| 5 | invalidate margins on scroll. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062144 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
}
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> invalidate margins on scroll.
<DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
+
+ foreach(var margin in LeftMargins)
+ {
+ margin.InvalidateVisual();
+ }
}
}
| 5 | invalidate margins on scroll. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062145 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
}
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> invalidate margins on scroll.
<DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
+
+ foreach(var margin in LeftMargins)
+ {
+ margin.InvalidateVisual();
+ }
}
}
| 5 | invalidate margins on scroll. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062146 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
}
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> invalidate margins on scroll.
<DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
+
+ foreach(var margin in LeftMargins)
+ {
+ margin.InvalidateVisual();
+ }
}
}
| 5 | invalidate margins on scroll. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062147 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
}
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> invalidate margins on scroll.
<DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
+
+ foreach(var margin in LeftMargins)
+ {
+ margin.InvalidateVisual();
+ }
}
}
| 5 | invalidate margins on scroll. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062148 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
}
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> invalidate margins on scroll.
<DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
+
+ foreach(var margin in LeftMargins)
+ {
+ margin.InvalidateVisual();
+ }
}
}
| 5 | invalidate margins on scroll. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062149 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
#endregion
#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately before the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
}
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> invalidate margins on scroll.
<DFF> @@ -1087,6 +1087,11 @@ namespace AvaloniaEdit.Editing
TextView.SetScrollOffset(new Vector(value.X, value.Y * TextView.DefaultLineHeight));
_offset = value;
+
+ foreach(var margin in LeftMargins)
+ {
+ margin.InvalidateVisual();
+ }
}
}
| 5 | invalidate margins on scroll. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.