Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix use of CoerceCaretIndex on Text change #2553

Merged
merged 4 commits into from
May 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions src/Avalonia.Controls/TextBox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -214,9 +214,9 @@ public string Text
if (!_ignoreTextChanges)
{
var caretIndex = CaretIndex;
SelectionStart = CoerceCaretIndex(SelectionStart, value?.Length ?? 0);
SelectionEnd = CoerceCaretIndex(SelectionEnd, value?.Length ?? 0);
CaretIndex = CoerceCaretIndex(caretIndex, value?.Length ?? 0);
SelectionStart = CoerceCaretIndex(SelectionStart, value);
SelectionEnd = CoerceCaretIndex(SelectionEnd, value);
CaretIndex = CoerceCaretIndex(caretIndex, value);

if (SetAndRaise(TextProperty, ref _text, value) && !_isUndoingRedoing)
{
Expand Down Expand Up @@ -677,11 +677,15 @@ protected override void UpdateDataValidation(AvaloniaProperty property, BindingN
}
}

private int CoerceCaretIndex(int value) => CoerceCaretIndex(value, Text?.Length ?? 0);
private int CoerceCaretIndex(int value) => CoerceCaretIndex(value, Text);

private int CoerceCaretIndex(int value, int length)
private int CoerceCaretIndex(int value, string text)
{
var text = Text;
if (text == null)
{
return 0;
}
var length = text.Length;

if (value < 0)
{
Expand All @@ -691,7 +695,7 @@ private int CoerceCaretIndex(int value, int length)
{
return length;
}
else if (value > 0 && text[value - 1] == '\r' && text[value] == '\n')
else if (value > 0 && text[value - 1] == '\r' && value < length && text[value] == '\n')
ahopper marked this conversation as resolved.
Show resolved Hide resolved
{
return value + 1;
}
Expand Down
15 changes: 15 additions & 0 deletions tests/Avalonia.Controls.UnitTests/TextBoxTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,21 @@ public void SelectionStartEnd_Are_Valid_AterTextChange()
Assert.True(target.SelectionEnd <= "123".Length);
}
}
[Fact]
public void CoerceCaretIndex_Doesnt_Cause_Exception_with_malformed_line_ending()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789\r"
};
target.CaretIndex = 11;

Assert.True(true);
}
}

private static TestServices Services => TestServices.MockThreadingInterface.With(
standardCursorFactory: Mock.Of<IStandardCursorFactory>());
Expand Down