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
|
---|---|---|---|---|---|---|---|---|
10065350 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065351 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065352 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065353 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065354 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065355 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065356 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065357 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065358 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065359 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065360 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065361 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065362 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065363 | <NME> LinkElementGenerator.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.Text.RegularExpressions;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
// This class is public because it can be used as a base class for custom links.
/// <summary>
/// Detects hyperlinks and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
// (this allows accepting punctuation inside links but not at the end)
internal readonly static Regex DefaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
// try to detect email addresses
internal readonly static Regex DefaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
private readonly Regex _linkRegex;
/// <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 new LinkElementGenerator.
/// </summary>
public LinkElementGenerator()
{
_linkRegex = DefaultLinkRegex;
RequireControlModifierForClick = true;
}
/// <summary>
/// Creates a new LinkElementGenerator using the specified regex.
/// </summary>
protected LinkElementGenerator(Regex regex) : this()
{
_linkRegex = regex ?? throw new ArgumentNullException(nameof(regex));
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
}
private Match GetMatch(int startOffset, out int matchOffset)
{
var endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
var relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
var m = _linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
return m;
}
/// <inheritdoc/>
public override int GetFirstInterestedOffset(int startOffset)
{
GetMatch(startOffset, out var matchOffset);
return matchOffset;
}
/// <inheritdoc/>
public override VisualLineElement ConstructElement(int offset)
{
var m = GetMatch(offset, out var matchOffset);
if (m.Success && matchOffset == offset) {
return ConstructElementFromMatch(m);
} else {
return null;
}
}
/// <summary>
/// Constructs a VisualLineElement that replaces the matched text.
/// The default implementation will create a <see cref="VisualLineLinkText"/>
/// based on the URI provided by <see cref="GetUriFromMatch"/>.
/// </summary>
protected virtual VisualLineElement ConstructElementFromMatch(Match m)
{
var uri = GetUriFromMatch(m);
if (uri == null)
return null;
var linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length)
{
NavigateUri = uri,
RequireControlModifierForClick = RequireControlModifierForClick
};
return linkText;
}
/// <summary>
/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
/// </summary>
protected virtual Uri GetUriFromMatch(Match match)
{
var targetUrl = match.Value;
if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
targetUrl = "http://" + targetUrl;
return Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute) ? new Uri(targetUrl) : null;
}
}
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Detects e-mail addresses and makes them clickable.
/// </summary>
/// <remarks>
/// This element generator can be easily enabled and configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
internal sealed class MailLinkElementGenerator : LinkElementGenerator
{
/// <summary>
/// Creates a new MailLinkElementGenerator.
/// </summary>
public MailLinkElementGenerator()
: base(DefaultMailRegex)
{
}
protected override Uri GetUriFromMatch(Match match)
{
return new Uri("mailto:" + match.Value);
}
}
}
<MSG> Check for valid mail URL before creating #105
https://github.com/icsharpcode/AvalonEdit/pull/105
<DFF> @@ -149,7 +149,11 @@ namespace AvaloniaEdit.Rendering
protected override Uri GetUriFromMatch(Match match)
{
- return new Uri("mailto:" + match.Value);
+ var targetUrl = "mailto:" + match.Value;
+ if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+ return new Uri(targetUrl);
+
+ return null;
}
}
}
| 5 | Check for valid mail URL before creating #105 | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065364 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065365 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065366 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065367 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065368 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065369 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065370 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065371 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065372 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065373 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065374 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065375 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065376 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065377 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065378 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
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)
| 15 | Merge branch 'fix-long-lines-support' of https://github.com/AvaloniaUI/AvaloniaEdit into fix-long-lines-support | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065379 | <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
This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:
```php
Dusterio\LumenPassport\LumenPassport::routes($this->app);
```
You can add that into an existing group, or add use this route registrar independently like so;
```php
Dusterio\LumenPassport\LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']);
```
## User model
```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> Merge pull request #81 from theissn/patch-1
Updated README Registering Routes example
<DFF> @@ -131,13 +131,13 @@ Next, you should call the LumenPassport::routes method within the boot method of
This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:
```php
-Dusterio\LumenPassport\LumenPassport::routes($this->app);
+\Dusterio\LumenPassport\LumenPassport::routes($this->app);
```
You can add that into an existing group, or add use this route registrar independently like so;
```php
-Dusterio\LumenPassport\LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']);
+\Dusterio\LumenPassport\LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']);
```
## User model
| 2 | Merge pull request #81 from theissn/patch-1 | 2 | .md | md | mit | dusterio/lumen-passport |
10065380 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065381 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065382 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065383 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065384 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065385 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065386 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065387 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065388 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065389 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065390 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065391 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065392 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065393 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065394 | <NME> SelectionMouseHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Input;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using System;
using System.ComponentModel;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Handles selection of text using the mouse.
/// </summary>
internal sealed class SelectionMouseHandler : ITextAreaInputHandler
{
#region enum SelectionMode
private enum SelectionMode
{
/// <summary>
/// no selection (no mouse button down)
/// </summary>
None,
/// <summary>
/// left mouse button down on selection, might be normal click
/// or might be drag'n'drop
/// </summary>
PossibleDragStart,
/// <summary>
/// dragging text
/// </summary>
Drag,
/// <summary>
/// normal selection (click+drag)
/// </summary>
Normal,
/// <summary>
/// whole-word selection (double click+drag or ctrl+click+drag)
/// </summary>
WholeWord,
/// <summary>
/// whole-line selection (triple click+drag)
/// </summary>
WholeLine,
/// <summary>
/// rectangular selection (alt+click+drag)
/// </summary>
Rectangular
}
#endregion
private SelectionMode _mode;
private AnchorSegment _startWord;
private Point _possibleDragStartMousePos;
#region Constructor + Attach + Detach
public SelectionMouseHandler(TextArea textArea)
{
TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
}
public TextArea TextArea { get; }
public void Attach()
{
TextArea.PointerPressed += TextArea_MouseLeftButtonDown;
TextArea.PointerMoved += TextArea_MouseMove;
TextArea.PointerReleased += TextArea_MouseLeftButtonUp;
//textArea.QueryCursor += textArea_QueryCursor;
TextArea.OptionChanged += TextArea_OptionChanged;
_enableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (_enableTextDragDrop)
{
AttachDragDrop();
}
}
public void Detach()
{
_mode = SelectionMode.None;
TextArea.PointerPressed -= TextArea_MouseLeftButtonDown;
TextArea.PointerMoved -= TextArea_MouseMove;
TextArea.PointerReleased -= TextArea_MouseLeftButtonUp;
//textArea.QueryCursor -= textArea_QueryCursor;
TextArea.OptionChanged -= TextArea_OptionChanged;
if (_enableTextDragDrop)
{
DetachDragDrop();
}
}
private void AttachDragDrop()
{
//textArea.AllowDrop = true;
//textArea.GiveFeedback += textArea_GiveFeedback;
//textArea.QueryContinueDrag += textArea_QueryContinueDrag;
//textArea.DragEnter += textArea_DragEnter;
//textArea.DragOver += textArea_DragOver;
//textArea.DragLeave += textArea_DragLeave;
//textArea.Drop += textArea_Drop;
}
private void DetachDragDrop()
{
//textArea.AllowDrop = false;
//textArea.GiveFeedback -= textArea_GiveFeedback;
//textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
//textArea.DragEnter -= textArea_DragEnter;
//textArea.DragOver -= textArea_DragOver;
//textArea.DragLeave -= textArea_DragLeave;
//textArea.Drop -= textArea_Drop;
}
private bool _enableTextDragDrop;
private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e)
{
var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop;
if (newEnableTextDragDrop != _enableTextDragDrop)
{
_enableTextDragDrop = newEnableTextDragDrop;
if (newEnableTextDragDrop)
AttachDragDrop();
else
DetachDragDrop();
}
}
#endregion
#region Dropping text
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragEnter(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// textArea.Caret.Show();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragOver(object sender, DragEventArgs e)
//{
// try {
// e.Effects = GetEffect(e);
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//DragDropEffects GetEffect(DragEventArgs e)
//{
// if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
// e.Handled = true;
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
// if (offset >= 0) {
// textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
// textArea.Caret.DesiredXPos = double.NaN;
// if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
// if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
// && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
// {
// return DragDropEffects.Move;
// } else {
// return e.AllowedEffects & DragDropEffects.Copy;
// }
// }
// }
// }
// return DragDropEffects.None;
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_DragLeave(object sender, DragEventArgs e)
//{
// try {
// e.Handled = true;
// if (!textArea.IsKeyboardFocusWithin)
// textArea.Caret.Hide();
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_Drop(object sender, DragEventArgs e)
//{
// try {
// DragDropEffects effect = GetEffect(e);
// e.Effects = effect;
// if (effect != DragDropEffects.None) {
// int start = textArea.Caret.Offset;
// if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
// Debug.WriteLine("Drop: did not drop: drop target is inside selection");
// e.Effects = DragDropEffects.None;
// } else {
// Debug.WriteLine("Drop: insert at " + start);
// var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
// textArea.RaiseEvent(pastingEventArgs);
// if (pastingEventArgs.CommandCancelled)
// return;
// string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
// if (text == null)
// return;
// bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
// // Mark the undo group with the currentDragDescriptor, if the drag
// // is originating from the same control. This allows combining
// // the undo groups when text is moved.
// textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
// try {
// if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
// } else {
// textArea.Document.Insert(start, text);
// textArea.Selection = Selection.Create(textArea, start, start + text.Length);
// }
// } finally {
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
// e.Handled = true;
// }
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//void OnDragException(Exception ex)
//{
// // swallows exceptions during drag'n'drop or reports them incorrectly, so
// // we re-throw them later to allow the application's unhandled exception handler
// // to catch them
// textArea.Dispatcher.BeginInvoke(
// DispatcherPriority.Send,
// new Action(delegate {
// throw new DragDropException("Exception during drag'n'drop", ex);
// }));
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
//{
// try {
// e.UseDefaultCursors = true;
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
//void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
//{
// try {
// if (e.EscapePressed) {
// e.Action = DragAction.Cancel;
// } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
// e.Action = DragAction.Drop;
// } else {
// e.Action = DragAction.Continue;
// }
// e.Handled = true;
// } catch (Exception ex) {
// OnDragException(ex);
// }
//}
#endregion
#region Start Drag
//object currentDragDescriptor;
//void StartDrag()
//{
// // prevent nested StartDrag calls
// mode = SelectionMode.Drag;
// // mouse capture and Drag'n'Drop doesn't mix
// textArea.ReleaseMouseCapture();
// DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
// DragDropEffects allowedEffects = DragDropEffects.All;
// var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
// foreach (ISegment s in deleteOnMove) {
// ISegment[] result = textArea.GetDeletableSegments(s);
// if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
// allowedEffects &= ~DragDropEffects.Move;
// }
// }
// var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
// textArea.RaiseEvent(copyingEventArgs);
// if (copyingEventArgs.CommandCancelled)
// return;
// object dragDescriptor = new object();
// this.currentDragDescriptor = dragDescriptor;
// DragDropEffects resultEffect;
// using (textArea.AllowCaretOutsideSelection()) {
// var oldCaretPosition = textArea.Caret.Position;
// try {
// Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
// resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
// Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
// } catch (COMException ex) {
// // ignore COM errors - don't crash on badly implemented drop targets
// Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
// return;
// }
// if (resultEffect == DragDropEffects.None) {
// // reset caret if drag was aborted
// textArea.Caret.Position = oldCaretPosition;
// }
// }
// this.currentDragDescriptor = null;
// if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
// bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.StartContinuedUndoGroup(null);
// textArea.Document.BeginUpdate();
// try {
// foreach (ISegment s in deleteOnMove) {
// textArea.Document.Remove(s.Offset, s.Length);
// }
// } finally {
// textArea.Document.EndUpdate();
// if (draggedInsideSingleDocument)
// textArea.Document.UndoStack.EndUndoGroup();
// }
// }
//}
#endregion
#region QueryCursor
// provide the IBeam Cursor for the text area
//void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
//{
// if (!e.Handled) {
// if (mode != SelectionMode.None) {
// // during selection, use IBeam cursor even outside the text area
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// } else if (textArea.TextView.VisualLinesValid) {
// // Only query the cursor if the visual lines are valid.
// // If they are invalid, the cursor will get re-queried when the visual lines
// // get refreshed.
// Point p = e.GetPosition(textArea.TextView);
// if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
// int visualColumn;
// bool isAtEndOfLine;
// int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
// if (enableTextDragDrop && textArea.Selection.Contains(offset))
// e.Cursor = Cursors.Arrow;
// else
// e.Cursor = Cursors.IBeam;
// e.Handled = true;
// }
// }
// }
//}
#endregion
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
TextArea.Cursor = Cursor.Parse("IBeam");
var pointer = e.GetPointerPoint(TextArea);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && !shift)
{
var offset = GetOffsetFromMousePosition(e, out _, out _);
if (TextArea.Selection.Contains(offset))
{
if (TextArea.CapturePointer(e.Pointer))
{
_mode = SelectionMode.PossibleDragStart;
_possibleDragStartMousePos = e.GetPosition(TextArea);
}
e.Handled = true;
return;
}
}
var oldPosition = TextArea.Caret.Position;
SetCaretOffsetToMousePosition(e);
if (!shift)
{
TextArea.ClearSelection();
}
if (TextArea.CapturePointer(e.Pointer))
{
if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
_mode = SelectionMode.Rectangular;
if (shift && TextArea.Selection is RectangleSelection)
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.WholeWord;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
{
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
}
else
{
SimpleSegment startWord;
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
if (e.ClickCount == 3)
{
_mode = SelectionMode.WholeLine;
startWord = GetLineAtMousePosition(e);
}
else
{
_mode = SelectionMode.WholeWord;
startWord = GetWordAtMousePosition(e);
}
if (startWord == SimpleSegment.Invalid)
{
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
return;
}
if (shift && !TextArea.Selection.IsEmpty)
{
if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
}
else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
{
TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
}
_startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
}
else
{
TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
_startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
}
e.Handled = true;
}
}
#endregion
}
}
}
#endregion
#region LeftButtonClick
#endregion
#region LeftButtonDoubleTap
#endregion
#region Mouse Position <-> Text coordinates
private SimpleSegment GetWordAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace);
var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordStartVc == -1)
wordStartVc = 0;
var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace);
if (wordEndVc == -1)
wordEndVc = line.VisualLength;
var relOffset = line.FirstDocumentLine.Offset;
var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset;
var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset;
return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
}
else
{
return SimpleSegment.Invalid;
}
}
private SimpleSegment GetLineAtMousePosition(PointerEventArgs e)
{
var textView = TextArea.TextView;
if (textView == null) return SimpleSegment.Invalid;
var pos = e.GetPosition(textView);
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
var line = textView.GetVisualLineFromVisualTop(pos.Y);
return line != null && line.TextLines != null
? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset)
: SimpleSegment.Invalid;
}
private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine)
{
return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine);
}
private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
isAtEndOfLine = false;
return -1;
}
private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
{
visualColumn = 0;
var textView = TextArea.TextView;
var pos = positionRelativeToTextView;
if (pos.Y < 0)
pos = pos.WithY(0);
if (pos.Y > textView.Bounds.Height)
pos = pos.WithY(textView.Bounds.Height);
pos += textView.ScrollOffset;
if (pos.Y >= textView.DocumentHeight)
pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon);
var line = textView.GetVisualLineFromVisualTop(pos.Y);
if (line != null && line.TextLines != null)
{
visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace);
return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
}
return -1;
}
#endregion
private const int MinimumHorizontalDragDistance = 2;
private const int MinimumVerticalDragDistance = 2;
#region MouseMove
private void TextArea_MouseMove(object sender, PointerEventArgs e)
{
if (e.Handled)
return;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular)
{
e.Handled = true;
if (TextArea.TextView.VisualLinesValid)
{
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
}
else if (_mode == SelectionMode.PossibleDragStart)
{
e.Handled = true;
Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance)
{
// TODO: drag
//StartDrag();
}
}
}
#endregion
#region ExtendSelection
private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null)
{
int visualColumn;
bool isAtEndOfLine;
int offset;
if (_mode == SelectionMode.Rectangular)
{
offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn);
isAtEndOfLine = true;
}
else
{
offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
}
if (allowedSegment != null)
{
offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
}
if (offset >= 0)
{
TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
TextArea.Caret.DesiredXPos = double.NaN;
}
}
private void ExtendSelectionToMouse(PointerEventArgs e)
{
var oldPosition = TextArea.Caret.Position;
if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular)
{
SetCaretOffsetToMousePosition(e);
if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection)
TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection))
TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position);
else
TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
}
else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine)
{
var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
if (newWord != SimpleSegment.Invalid && _startWord != null)
{
TextArea.Selection = Selection.Create(TextArea,
Math.Min(newWord.Offset, _startWord.Offset),
Math.Max(newWord.EndOffset, _startWord.EndOffset));
// moves caret to start or end of selection
TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset);
}
}
TextArea.Caret.BringCaretToView(0);
}
#endregion
#region MouseLeftButtonUp
private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e)
{
if (_mode == SelectionMode.None || e.Handled)
return;
e.Handled = true;
switch (_mode)
{
case SelectionMode.PossibleDragStart:
// this was not a drag start (mouse didn't move after mousedown)
SetCaretOffsetToMousePosition(e);
TextArea.ClearSelection();
break;
case SelectionMode.Normal:
case SelectionMode.WholeWord:
case SelectionMode.WholeLine:
case SelectionMode.Rectangular:
if (TextArea.Options.ExtendSelectionOnMouseUp)
ExtendSelectionToMouse(e);
break;
}
_mode = SelectionMode.None;
TextArea.ReleasePointerCapture(e.Pointer);
}
#endregion
}
}
<MSG> Merge pull request #158 from Takoooooo/fix-selection-issues
Fix selection issues
<DFF> @@ -392,110 +392,113 @@ namespace AvaloniaEdit.Editing
private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e)
{
- TextArea.Cursor = Cursor.Parse("IBeam");
+ if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed)
+ {
+ TextArea.Cursor = Cursor.Parse("IBeam");
- var pointer = e.GetPointerPoint(TextArea);
+ var pointer = e.GetPointerPoint(TextArea);
- _mode = SelectionMode.None;
- if (!e.Handled)
- {
- var modifiers = e.KeyModifiers;
- var shift = modifiers.HasFlag(KeyModifiers.Shift);
- if (_enableTextDragDrop && !shift)
+ _mode = SelectionMode.None;
+ if (!e.Handled)
{
- var offset = GetOffsetFromMousePosition(e, out _, out _);
- if (TextArea.Selection.Contains(offset))
+ var modifiers = e.KeyModifiers;
+ var shift = modifiers.HasFlag(KeyModifiers.Shift);
+ if (_enableTextDragDrop && !shift)
{
- if (TextArea.CapturePointer(e.Pointer))
+ var offset = GetOffsetFromMousePosition(e, out _, out _);
+ if (TextArea.Selection.Contains(offset))
{
- _mode = SelectionMode.PossibleDragStart;
- _possibleDragStartMousePos = e.GetPosition(TextArea);
+ if (TextArea.CapturePointer(e.Pointer))
+ {
+ _mode = SelectionMode.PossibleDragStart;
+ _possibleDragStartMousePos = e.GetPosition(TextArea);
+ }
+ e.Handled = true;
+ return;
}
- e.Handled = true;
- return;
}
- }
-
- var oldPosition = TextArea.Caret.Position;
- SetCaretOffsetToMousePosition(e);
+ var oldPosition = TextArea.Caret.Position;
+ SetCaretOffsetToMousePosition(e);
- if (!shift)
- {
- TextArea.ClearSelection();
- }
- if (TextArea.CapturePointer(e.Pointer))
- {
- if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
+ if (!shift)
{
- _mode = SelectionMode.Rectangular;
- if (shift && TextArea.Selection is RectangleSelection)
- {
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
- }
+ TextArea.ClearSelection();
}
- else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
+
+ if (TextArea.CapturePointer(e.Pointer))
{
- _mode = SelectionMode.WholeWord;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection)
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.Rectangular;
+ if (shift && TextArea.Selection is RectangleSelection)
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else if(pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
- {
- _mode = SelectionMode.Normal;
- if (shift && !(TextArea.Selection is RectangleSelection))
+ else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1
{
- TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
- }
- else
- {
- SimpleSegment startWord;
-
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
-
- if (e.ClickCount == 3)
+ else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1
{
- _mode = SelectionMode.WholeLine;
- startWord = GetLineAtMousePosition(e);
+ _mode = SelectionMode.Normal;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
}
else
{
- _mode = SelectionMode.WholeWord;
- startWord = GetWordAtMousePosition(e);
- }
-
- if (startWord == SimpleSegment.Invalid)
- {
- _mode = SelectionMode.None;
- TextArea.ReleasePointerCapture(e.Pointer);
- return;
- }
- if (shift && !TextArea.Selection.IsEmpty)
- {
- if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ SimpleSegment startWord;
+
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+
+ if (e.ClickCount == 3)
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ _mode = SelectionMode.WholeLine;
+ startWord = GetLineAtMousePosition(e);
}
- else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ else
{
- TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ _mode = SelectionMode.WholeWord;
+ startWord = GetWordAtMousePosition(e);
+ }
+
+ if (startWord == SimpleSegment.Invalid)
+ {
+ _mode = SelectionMode.None;
+ TextArea.ReleasePointerCapture(e.Pointer);
+ return;
+ }
+ if (shift && !TextArea.Selection.IsEmpty)
+ {
+ if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset)));
+ }
+ else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset)
+ {
+ TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset)));
+ }
+ _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
+ }
+ else
+ {
+ TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
+ _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
- _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment);
- }
- else
- {
- TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset);
- _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length);
}
}
+ e.Handled = true;
}
- e.Handled = true;
- }
+ }
}
#endregion
| 79 | Merge pull request #158 from Takoooooo/fix-selection-issues | 76 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065395 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065396 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065397 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065398 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065399 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065400 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065401 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065402 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065403 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065404 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065405 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065406 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065407 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065408 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065409 | <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);
}
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
#endregion
#region Focus Handling (Show/Hide Caret)
/// <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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.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> feature
<DFF> @@ -708,6 +708,21 @@ namespace AvaloniaEdit.Editing
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
+
+ /// <summary>
+ /// The <see cref="IsRightClickMovesCaret"/> property.
+ /// </summary>
+ public static readonly StyledProperty<bool> IsRightClickMovesCaretProperty =
+ AvaloniaProperty.Register<TextArea, bool>(nameof(IsRightClickMovesCaret), false);
+
+ /// <summary>
+ /// Determines whether caret position should be changed to the mouse position when you right click or not.
+ /// </summary>
+ public bool IsRightClickMovesCaret
+ {
+ get => GetValue(IsRightClickMovesCaretProperty);
+ set => SetValue(IsRightClickMovesCaretProperty, value);
+ }
#endregion
#region Focus Handling (Show/Hide Caret)
| 15 | feature | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065410 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065411 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065412 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065413 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065414 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065415 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065416 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065417 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065418 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065419 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065420 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065421 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065422 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065423 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065424 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Use Watermark instead of TextBoxWithLable
<DFF> @@ -61,7 +61,7 @@
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
- <search:TextBoxWithLabel Label="{x:Static ae:SR.SearchLabel}"
+ <TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
@@ -111,7 +111,7 @@
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
- <search:TextBoxWithLabel Name="ReplaceBox" Label="{x:Static ae:SR.ReplaceLabel}"
+ <TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
| 2 | Use Watermark instead of TextBoxWithLable | 2 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10065425 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065426 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065427 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065428 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065429 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065430 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065431 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065432 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065433 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065434 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065435 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065436 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065437 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065438 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065439 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
</PropertyGroup>
</Project>
<VersionSuffix>beta</VersionSuffix>
</PropertyGroup>
</Project>
<MSG> update to preview 3
<DFF> @@ -2,6 +2,6 @@
<PropertyGroup>
<LangVersion>7.1</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
- <AvaloniaVersion>0.9.0-preview2</AvaloniaVersion>
+ <AvaloniaVersion>0.9.0-preview3</AvaloniaVersion>
</PropertyGroup>
</Project>
\ No newline at end of file
| 1 | update to preview 3 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
10065440 | <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.
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
#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
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
internal void OnTextCopied(TextEventArgs e)
|| 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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
public void RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
}
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> Merge pull request #106 from Deadpikle/fix/105
Use logical scrollable to invalidate scroll in TextArea
<DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
- private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
@@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing
event EventHandler ILogicalScrollable.ScrollInvalidated
{
- add => _scrollInvalidated += value;
- remove => _scrollInvalidated -= value;
+ add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
+ remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
@@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing
public void RaiseScrollInvalidated(EventArgs e)
{
- _scrollInvalidated?.Invoke(this, e);
+ _logicalScrollable?.RaiseScrollInvalidated(e);
}
}
| 3 | Merge pull request #106 from Deadpikle/fix/105 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065441 | <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.
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
#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
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
internal void OnTextCopied(TextEventArgs e)
|| 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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
public void RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
}
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> Merge pull request #106 from Deadpikle/fix/105
Use logical scrollable to invalidate scroll in TextArea
<DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
- private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
@@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing
event EventHandler ILogicalScrollable.ScrollInvalidated
{
- add => _scrollInvalidated += value;
- remove => _scrollInvalidated -= value;
+ add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
+ remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
@@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing
public void RaiseScrollInvalidated(EventArgs e)
{
- _scrollInvalidated?.Invoke(this, e);
+ _logicalScrollable?.RaiseScrollInvalidated(e);
}
}
| 3 | Merge pull request #106 from Deadpikle/fix/105 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065442 | <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.
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
#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
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
internal void OnTextCopied(TextEventArgs e)
|| 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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
public void RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
}
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> Merge pull request #106 from Deadpikle/fix/105
Use logical scrollable to invalidate scroll in TextArea
<DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
- private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
@@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing
event EventHandler ILogicalScrollable.ScrollInvalidated
{
- add => _scrollInvalidated += value;
- remove => _scrollInvalidated -= value;
+ add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
+ remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
@@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing
public void RaiseScrollInvalidated(EventArgs e)
{
- _scrollInvalidated?.Invoke(this, e);
+ _logicalScrollable?.RaiseScrollInvalidated(e);
}
}
| 3 | Merge pull request #106 from Deadpikle/fix/105 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065443 | <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.
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
#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
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
internal void OnTextCopied(TextEventArgs e)
|| 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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
public void RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
}
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> Merge pull request #106 from Deadpikle/fix/105
Use logical scrollable to invalidate scroll in TextArea
<DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
- private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
@@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing
event EventHandler ILogicalScrollable.ScrollInvalidated
{
- add => _scrollInvalidated += value;
- remove => _scrollInvalidated -= value;
+ add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
+ remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
@@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing
public void RaiseScrollInvalidated(EventArgs e)
{
- _scrollInvalidated?.Invoke(this, e);
+ _logicalScrollable?.RaiseScrollInvalidated(e);
}
}
| 3 | Merge pull request #106 from Deadpikle/fix/105 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065444 | <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.
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
#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
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
internal void OnTextCopied(TextEventArgs e)
|| 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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
public void RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
}
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> Merge pull request #106 from Deadpikle/fix/105
Use logical scrollable to invalidate scroll in TextArea
<DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
- private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
@@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing
event EventHandler ILogicalScrollable.ScrollInvalidated
{
- add => _scrollInvalidated += value;
- remove => _scrollInvalidated -= value;
+ add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
+ remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
@@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing
public void RaiseScrollInvalidated(EventArgs e)
{
- _scrollInvalidated?.Invoke(this, e);
+ _logicalScrollable?.RaiseScrollInvalidated(e);
}
}
| 3 | Merge pull request #106 from Deadpikle/fix/105 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065445 | <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.
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
#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
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
internal void OnTextCopied(TextEventArgs e)
|| 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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
public void RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
}
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> Merge pull request #106 from Deadpikle/fix/105
Use logical scrollable to invalidate scroll in TextArea
<DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
- private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
@@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing
event EventHandler ILogicalScrollable.ScrollInvalidated
{
- add => _scrollInvalidated += value;
- remove => _scrollInvalidated -= value;
+ add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
+ remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
@@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing
public void RaiseScrollInvalidated(EventArgs e)
{
- _scrollInvalidated?.Invoke(this, e);
+ _logicalScrollable?.RaiseScrollInvalidated(e);
}
}
| 3 | Merge pull request #106 from Deadpikle/fix/105 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065446 | <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.
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
#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
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
internal void OnTextCopied(TextEventArgs e)
|| 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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
public void RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
}
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> Merge pull request #106 from Deadpikle/fix/105
Use logical scrollable to invalidate scroll in TextArea
<DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
- private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
@@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing
event EventHandler ILogicalScrollable.ScrollInvalidated
{
- add => _scrollInvalidated += value;
- remove => _scrollInvalidated -= value;
+ add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
+ remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
@@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing
public void RaiseScrollInvalidated(EventArgs e)
{
- _scrollInvalidated?.Invoke(this, e);
+ _logicalScrollable?.RaiseScrollInvalidated(e);
}
}
| 3 | Merge pull request #106 from Deadpikle/fix/105 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065447 | <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.
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
#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
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
internal void OnTextCopied(TextEventArgs e)
|| 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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
public void RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
}
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> Merge pull request #106 from Deadpikle/fix/105
Use logical scrollable to invalidate scroll in TextArea
<DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
- private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
@@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing
event EventHandler ILogicalScrollable.ScrollInvalidated
{
- add => _scrollInvalidated += value;
- remove => _scrollInvalidated -= value;
+ add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
+ remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
@@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing
public void RaiseScrollInvalidated(EventArgs e)
{
- _scrollInvalidated?.Invoke(this, e);
+ _logicalScrollable?.RaiseScrollInvalidated(e);
}
}
| 3 | Merge pull request #106 from Deadpikle/fix/105 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065448 | <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.
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
#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
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
internal void OnTextCopied(TextEventArgs e)
|| 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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
public void RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
}
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> Merge pull request #106 from Deadpikle/fix/105
Use logical scrollable to invalidate scroll in TextArea
<DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
- private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
@@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing
event EventHandler ILogicalScrollable.ScrollInvalidated
{
- add => _scrollInvalidated += value;
- remove => _scrollInvalidated -= value;
+ add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
+ remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
@@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing
public void RaiseScrollInvalidated(EventArgs e)
{
- _scrollInvalidated?.Invoke(this, e);
+ _logicalScrollable?.RaiseScrollInvalidated(e);
}
}
| 3 | Merge pull request #106 from Deadpikle/fix/105 | 4 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10065449 | <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.
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
#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
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
internal void OnTextCopied(TextEventArgs e)
|| 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);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
public void RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
}
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> Merge pull request #106 from Deadpikle/fix/105
Use logical scrollable to invalidate scroll in TextArea
<DFF> @@ -53,7 +53,6 @@ namespace AvaloniaEdit.Editing
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
- private EventHandler _scrollInvalidated;
#region Constructor
static TextArea()
@@ -1035,8 +1034,8 @@ namespace AvaloniaEdit.Editing
event EventHandler ILogicalScrollable.ScrollInvalidated
{
- add => _scrollInvalidated += value;
- remove => _scrollInvalidated -= value;
+ add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
+ remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
@@ -1100,7 +1099,7 @@ namespace AvaloniaEdit.Editing
public void RaiseScrollInvalidated(EventArgs e)
{
- _scrollInvalidated?.Invoke(this, e);
+ _logicalScrollable?.RaiseScrollInvalidated(e);
}
}
| 3 | Merge pull request #106 from Deadpikle/fix/105 | 4 | .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.