From 6938673c35a844b722611f15a95def25be3f25f1 Mon Sep 17 00:00:00 2001 From: nea Date: Sat, 30 Oct 2021 03:14:28 +0200 Subject: Make caret position movable by clicks Also deprecated the public getCaretPos method since it was public. --- .../cottonmc/cotton/gui/widget/WTextField.java | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/github/cottonmc/cotton/gui/widget/WTextField.java b/src/main/java/io/github/cottonmc/cotton/gui/widget/WTextField.java index c0ef7c2..3ea2123 100644 --- a/src/main/java/io/github/cottonmc/cotton/gui/widget/WTextField.java +++ b/src/main/java/io/github/cottonmc/cotton/gui/widget/WTextField.java @@ -127,6 +127,7 @@ public class WTextField extends WWidget { return this.cursor; } + @Environment(EnvType.CLIENT) public void scrollCursorIntoView() { if (scrollOffset > cursor) { scrollOffset = cursor; @@ -322,11 +323,28 @@ public class WTextField extends WWidget { @Override public InputResult onClick(int x, int y, int button) { requestFocus(); - cursor = getCaretPos(this.text, x - TEXT_PADDING_X); + cursor = getCaretPosition(x - TEXT_PADDING_X); scrollCursorIntoView(); return InputResult.PROCESSED; } + @Environment(EnvType.CLIENT) + public int getCaretPosition(int clickX) { + if (clickX < 0) return 0; + int lastPos = 0; + String string = text.substring(scrollOffset); + for (int i = 0; i < string.length(); i++) { + int w = font.getWidth(string.charAt(i) + ""); + if (lastPos + w >= clickX) { + if (clickX - lastPos < w / 2) { + return i + scrollOffset; + } + } + lastPos += w; + } + return string.length(); + } + @Environment(EnvType.CLIENT) @Override public void onCharTyped(char ch) { @@ -474,6 +492,7 @@ public class WTextField extends WWidget { * @return */ @Environment(EnvType.CLIENT) + @Deprecated public static int getCaretPos(String s, int x) { if (x <= 0) return 0; -- cgit