From 1c3fe03bf83f1772993de88434accde970863b77 Mon Sep 17 00:00:00 2001 From: Lulonaut <67191924+Lulonaut@users.noreply.github.com> Date: Wed, 1 Jun 2022 08:32:09 +0200 Subject: Override selected text when pasting in Item editor (#150) * replace selected text * crash when selection starts from the left * cursor pos crash --- .../itemeditor/GuiElementTextField.java | 25 +++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/github/moulberry/notenoughupdates/itemeditor/GuiElementTextField.java b/src/main/java/io/github/moulberry/notenoughupdates/itemeditor/GuiElementTextField.java index aa88cb77..f37f2fa1 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/itemeditor/GuiElementTextField.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/itemeditor/GuiElementTextField.java @@ -158,7 +158,12 @@ public class GuiElementTextField extends GuiElement { String textNC = textNoColour.substring(0, cursorIndex); int colorCodes = StringUtils.countMatches(textNC, "\u00B6"); - String line = text.substring(cursorIndex + (((options & COLOUR) != 0) ? colorCodes * 2 : 0)).split("\n")[0]; + String[] lines = text.substring(cursorIndex + (((options & COLOUR) != 0) ? colorCodes * 2 : 0)).split("\n"); + if (lines.length < 1) { + return 0; + } + String line = lines[0]; + int padding = Math.min(5, searchBarXSize - strLenNoColor(line)) / 2; String trimmed = Minecraft.getMinecraft().fontRendererObj.trimStringToWidth(line, xComp - padding); int linePos = strLenNoColor(trimmed); @@ -213,16 +218,26 @@ public class GuiElementTextField extends GuiElement { //allows for pasting formatted text that includes "§" if (GuiScreen.isKeyComboCtrlV(keyCode)) { textField.setEnabled(false); - //The cursor position gets set to the end when using setText - int oldCursorPosition = textField.getCursorPosition(); + + int selectionEnd = textField.getSelectionEnd(); + int cursorPosition = textField.getCursorPosition(); + + if (cursorPosition < selectionEnd) { + //swap selectionEnd and cursorPosition + selectionEnd = selectionEnd ^ cursorPosition; + cursorPosition = selectionEnd ^ cursorPosition; + selectionEnd = selectionEnd ^ cursorPosition; + } String clipboardContent = GuiScreen.getClipboardString(); + StringBuilder stringBuilder = new StringBuilder(getText()) - .insert(textField.getCursorPosition(), clipboardContent); + .replace(selectionEnd, cursorPosition, "") + .insert(selectionEnd, clipboardContent); //writeText removes unwanted chars from the String which includes "§" textField.setText(stringBuilder.toString()); - textField.setCursorPosition(oldCursorPosition + clipboardContent.length()); + textField.setCursorPosition(selectionEnd + clipboardContent.length()); } else { textField.setEnabled(true); } -- cgit