Add ImString resize support

This commit is contained in:
SpaiR committed 2020-01-01 13:41:44 +03:00
1 parent 295471930f
commit fbf1c0d1c2
4 files changed
+155 -103

No files matched your search

+52 -15
View File
@@ -1,20 +1,30 @@
package imgui;
import java.util.Arrays;
import java.util.Objects;
/**
* Wrapper for {@link String} to use inside of ImGui input widgets.
*/
public final class ImString {
private static final int DEFAULT_SIZE = 100;
private static final short DEFAULT_LENGTH = 100;
private static final short CARET_LEN = 1;
private static final short DEFAULT_RESIZE = 10;
public final ImGuiInputTextData inputData = new ImGuiInputTextData();
/**
* String will be resized to the value equal to a new size plus this resize factor.
*/
public int resizeFactor = DEFAULT_RESIZE;
ImGuiInputTextData inputData = new ImGuiInputTextData();
byte[] data;
private String text;
private String text = "";
public ImString() {
this(DEFAULT_SIZE);
this(DEFAULT_LENGTH);
}
public ImString(int size) {
data = new byte[size];
public ImString(int length) {
data = new byte[length + CARET_LEN];
}
public ImString(String text) {
@@ -22,8 +32,8 @@ public final class ImString {
set(text);
}
public ImString(String text, int size) {
this(size);
public ImString(String text, int length) {
this(length);
set(text);
}
@@ -36,11 +46,38 @@ public final class ImString {
}
public void set(String value) {
inputData.size = value.length();
text = value;
for (int i = 0; i < inputData.size; i++) {
data[i] = (byte) value.charAt(i);
set(value.getBytes());
}
public void set(String value, boolean resize) {
byte[] str = value.getBytes();
if (resize && data.length - CARET_LEN < str.length) {
data = new byte[str.length + resizeFactor + CARET_LEN];
}
set(str);
}
/**
* Get the length of the text inside of the data buffer.
* @return length of the text inside of the data buffer
*/
public int getLength() {
return get().length();
}
/**
* Get the size of the data buffer. Buffer size will always have '+1' to its size, since it's used by the Dear ImGui to draw a caret.
* @return size of the data buffer
*/
public int getBufferSize() {
return data.length;
}
private void set(byte[] str) {
int len = Math.min(str.length, data.length);
System.arraycopy(str, 0, data, 0, len);
inputData.isDirty = true;
inputData.size = len;
}
@Override
@@ -53,11 +90,11 @@ public final class ImString {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ImString imString = (ImString) o;
return Arrays.equals(data, imString.data);
return Objects.equals(text, imString.text);
}
@Override
public int hashCode() {
return Arrays.hashCode(data);
return text.hashCode();
}
}