Skip to content

Commit

Permalink
Merge pull request #5823 from peppy/select-all-textbox
Browse files Browse the repository at this point in the history
Allow selecting all text in a textbox programatically
  • Loading branch information
frenzibyte authored Oct 30, 2023
2 parents b772488 + 0cf3239 commit f1981a3
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
27 changes: 27 additions & 0 deletions osu.Framework.Tests/Visual/UserInterface/TestSceneTextBox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,33 @@ public void TestSetTextSelection()
AddAssert("nothing selected", () => textBox.SelectedText == string.Empty);
}

[Test]
public void TestSelectAll()
{
TextBox textBox = null;

AddStep("add textbox", () =>
{
textBoxes.Add(textBox = new BasicTextBox
{
Size = new Vector2(300, 40),
Text = "initial text",
});
});

AddAssert("select all fails", () => textBox.SelectAll(), () => Is.False);
AddAssert("no text selected", () => textBox.SelectedText, () => Is.EqualTo(string.Empty));

AddStep("click on textbox", () =>
{
InputManager.MoveMouseTo(textBox);
InputManager.Click(MouseButton.Left);
});

AddAssert("select all succeeds", () => textBox.SelectAll(), () => Is.True);
AddAssert("all text selected", () => textBox.SelectedText, () => Is.EqualTo(textBox.Text));
}

private void prependString(InsertableTextBox textBox, string text)
{
InputManager.Keys(PlatformAction.MoveBackwardLine);
Expand Down
19 changes: 16 additions & 3 deletions osu.Framework/Graphics/UserInterface/TextBox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -265,9 +265,7 @@ public virtual bool OnPressed(KeyBindingPressEvent<PlatformAction> e)
return true;

case PlatformAction.SelectAll:
selectionStart = 0;
selectionEnd = text.Length;
cursorAndLayout.Invalidate();
SelectAll();
onTextSelectionChanged(TextSelectionType.All, lastSelectionBounds);
return true;

Expand Down Expand Up @@ -362,6 +360,21 @@ public virtual void OnReleased(KeyBindingReleaseEvent<PlatformAction> e)
{
}

/// <summary>
/// Selects all text in this <see cref="TextBox"/>. Focus must be acquired before calling this method.
/// </summary>
/// <returns>Whether text has been selected successfully. Returns <c>false</c> if the text box does not have focus.</returns>
public bool SelectAll()
{
if (!HasFocus)
return false;

selectionStart = 0;
selectionEnd = text.Length;
cursorAndLayout.Invalidate();
return true;
}

/// <summary>
/// Find the word boundary in the backward direction, then return the negative amount of characters.
/// </summary>
Expand Down

0 comments on commit f1981a3

Please sign in to comment.