added text based ui

master
Moritz 2026-11-15 16:31:42 +01:00
parent c572eee5c5
commit 1e5f800c26
2 changed files with 348 additions and 14 deletions

View File

@ -6,6 +6,7 @@ public class config_editor {
public static ConfigFileType config_file_type;
static java.io.File config_file;
static Map<String, Object> config_data;
static Map<String, Object> config_data_edited;
enum ConfigFileType {
JSONC,
@ -17,7 +18,11 @@ public class config_editor {
verify_config_file();
config_file_type();
parse_config_file();
print_config_data();
if (args.length > 1 && args[1].equals("--Gui")) {
return;
}
config_data_edited = user_interface.run(config_data);
}
static void verify_config_file() {
@ -50,26 +55,15 @@ public class config_editor {
switch (config_file_type) {
case JSONC:
config_data = jsonc_parse.parse_file(config_file_path);
config_data_edited = jsonc_parse.parse_file(config_file_path);
break;
case XML:
config_data = xml_parse.parse_file(config_file_path);
config_data_edited = xml_parse.parse_file(config_file_path);
break;
default:
System.err.println("No valid config file type detected.");
}
}
static void print_config_data() {
for (Map.Entry<String, Object> entry : config_data.entrySet()) {
System.out.println(entry.getKey());
if (entry.getValue() instanceof Map<?, ?>) {
Map<?, ?> nestedMap = (Map<?, ?>) entry.getValue();
for (Map.Entry<?, ?> nestedEntry : nestedMap.entrySet()) {
System.out.println(" " + nestedEntry.getKey() + ": " + nestedEntry.getValue());
}
} else {
System.out.println(" " + entry.getValue());
}
}
}
}

View File

@ -0,0 +1,340 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class user_interface {
private static final int KEY_BASE = 0x110000;
private static final int KEY_UP = KEY_BASE;
private static final int KEY_DOWN = KEY_BASE + 1;
private static final int KEY_LEFT = KEY_BASE + 2;
private static final int KEY_RIGHT = KEY_BASE + 3;
private static final int KEY_HOME = KEY_BASE + 4;
private static final int KEY_END = KEY_BASE + 5;
private static final int KEY_DELETE = KEY_BASE + 6;
private static final int KEY_CTRL_A = KEY_BASE + 7;
public static Map<String, Object> run(Map<String, Object> configData) throws IOException {
if (configData == null) {
throw new IllegalArgumentException("Config data must not be null.");
}
if (!System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("windows")) {
throw new UnsupportedOperationException(
"The terminal UI currently requires Windows PowerShell.");
}
if (System.console() == null) {
throw new IllegalStateException(
"Run the config editor from an interactive PowerShell terminal.");
}
List<ValueEntry> entries = new ArrayList<ValueEntry>();
collectMap(configData, "", entries);
int selected = 0;
EditSession edit = null;
String status = "";
try (TerminalInput input = TerminalInput.start()) {
while (true) {
render(entries, selected, edit, status);
int key = input.readKey();
if (key == 3) {
break;
}
if (edit != null) {
if (key == 13) {
try {
edit.entry.setValue(parseEditedValue(edit.entry.value, edit.text.toString()));
status = "Updated " + edit.entry.path;
edit = null;
} catch (NumberFormatException exception) {
status = "Enter a valid value for this number.";
}
} else if (key == 27) {
status = "Edit cancelled.";
edit = null;
} else if (key == 8) {
if (edit.cursor > 0) {
edit.text.deleteCharAt(--edit.cursor);
}
} else if (key == KEY_DELETE) {
if (edit.cursor < edit.text.length()) {
edit.text.deleteCharAt(edit.cursor);
}
} else if (key == KEY_LEFT) {
edit.cursor = Math.max(0, edit.cursor - 1);
} else if (key == KEY_RIGHT) {
edit.cursor = Math.min(edit.text.length(), edit.cursor + 1);
} else if (key == KEY_HOME) {
edit.cursor = 0;
} else if (key == KEY_END) {
edit.cursor = edit.text.length();
} else if (key == KEY_CTRL_A) {
edit.text.setLength(0);
edit.cursor = 0;
} else if (key >= 0x20 && key <= Character.MAX_VALUE) {
edit.text.insert(edit.cursor++, (char) key);
}
continue;
}
if (key == KEY_UP) {
selected = Math.max(0, selected - 1);
status = "";
} else if (key == KEY_DOWN) {
selected = Math.min(entries.size() - 1, selected + 1);
status = "";
} else if (key == 13 && !entries.isEmpty()) {
ValueEntry entry = entries.get(selected);
if (isBooleanValue(entry.value)) {
entry.setValue(toggleBoolean(entry.value));
status = "Updated " + entry.path;
} else if (entry.setter == null) {
status = "Empty containers cannot be edited.";
} else {
edit = new EditSession(entry);
status = "Enter saves; Esc cancels; Ctrl+A clears.";
}
} else if (key == 27 || key == 'q' || key == 'Q') {
break;
}
}
}
System.out.print("\u001b[0m\n");
return configData;
}
private static void collectMap(
Map<String, Object> map, String parentPath, List<ValueEntry> entries) {
if (map.isEmpty() && !parentPath.isEmpty()) {
entries.add(new ValueEntry(parentPath, map, null));
return;
}
for (Map.Entry<String, Object> item : map.entrySet()) {
final String key = item.getKey();
final String path = parentPath.isEmpty() ? key : parentPath + "." + key;
final Map<String, Object> parent = map;
ValueSetter setter = new ValueSetter() {
@Override
public void set(Object value) {
parent.put(key, value);
}
};
collectValue(item.getValue(), path, setter, entries);
}
}
private static void collectList(List<Object> list, String parentPath, List<ValueEntry> entries) {
if (list.isEmpty()) {
entries.add(new ValueEntry(parentPath, list, null));
return;
}
for (int i = 0; i < list.size(); i++) {
final int index = i;
final List<Object> parent = list;
ValueSetter setter = new ValueSetter() {
@Override
public void set(Object value) {
parent.set(index, value);
}
};
collectValue(list.get(i), parentPath + "[" + i + "]", setter, entries);
}
}
private static void collectValue(
Object value, String path, ValueSetter setter, List<ValueEntry> entries) {
if (value instanceof Map<?, ?>) {
Map<String, Object> nestedMap = copyStringKeyedMap((Map<?, ?>) value);
setter.set(nestedMap);
collectMap(nestedMap, path, entries);
} else if (value instanceof List<?>) {
List<Object> nestedList = new ArrayList<Object>((List<?>) value);
setter.set(nestedList);
collectList(nestedList, path, entries);
} else {
entries.add(new ValueEntry(path, value, setter));
}
}
private static Map<String, Object> copyStringKeyedMap(Map<?, ?> source) {
Map<String, Object> copy = new java.util.LinkedHashMap<String, Object>();
for (Map.Entry<?, ?> entry : source.entrySet()) {
if (!(entry.getKey() instanceof String)) {
throw new IllegalArgumentException("Config map keys must be strings.");
}
copy.put((String) entry.getKey(), entry.getValue());
}
return copy;
}
private static boolean isBooleanValue(Object value) {
return value instanceof Boolean
|| value instanceof String
&& ("true".equalsIgnoreCase(((String) value).trim())
|| "false".equalsIgnoreCase(((String) value).trim()));
}
private static Object toggleBoolean(Object value) {
if (value instanceof Boolean) {
return !((Boolean) value);
}
return "true".equalsIgnoreCase(((String) value).trim()) ? "false" : "true";
}
private static Object parseEditedValue(Object oldValue, String text) {
String numericText = text.trim();
if (oldValue instanceof Integer) {
return Integer.valueOf(numericText);
}
if (oldValue instanceof Long) {
return Long.valueOf(numericText);
}
if (oldValue instanceof Short) {
return Short.valueOf(numericText);
}
if (oldValue instanceof Byte) {
return Byte.valueOf(numericText);
}
if (oldValue instanceof BigInteger) {
return new BigInteger(numericText);
}
if (oldValue instanceof BigDecimal) {
return new BigDecimal(numericText);
}
if (oldValue instanceof Float) {
return Float.valueOf(numericText);
}
if (oldValue instanceof Double) {
return Double.valueOf(numericText);
}
return text;
}
private static void render(
List<ValueEntry> entries, int selected, EditSession edit, String status) {
System.out.print("\u001b[2J\u001b[H");
System.out.println("Config editor | Up/Down: navigate Enter: edit/toggle q/Esc: quit");
System.out.println("While editing: Enter: save Esc: cancel arrows: move cursor Backspace/Delete: edit");
System.out.println();
for (int i = 0; i < entries.size(); i++) {
ValueEntry entry = entries.get(i);
System.out.print(i == selected ? "> " : " ");
System.out.print(safeDisplay(entry.path) + " = ");
if (edit != null && i == selected) {
String beforeCursor = edit.text.substring(0, edit.cursor);
String afterCursor = edit.text.substring(edit.cursor);
System.out.println(safeDisplay(beforeCursor) + "|" + safeDisplay(afterCursor));
} else {
System.out.println(safeDisplay(String.valueOf(entry.value)));
}
}
if (!status.isEmpty()) {
System.out.println();
System.out.println(status);
}
System.out.flush();
}
private static String safeDisplay(String value) {
return value.replace("\r", "\\r").replace("\n", "\\n").replace("\t", "\\t");
}
private interface ValueSetter {
void set(Object value);
}
private static class ValueEntry {
private final String path;
private final ValueSetter setter;
private Object value;
ValueEntry(String path, Object value, ValueSetter setter) {
this.path = path;
this.value = value;
this.setter = setter;
}
void setValue(Object value) {
setter.set(value);
this.value = value;
}
}
private static class EditSession {
private final ValueEntry entry;
private final StringBuilder text;
private int cursor;
EditSession(ValueEntry entry) {
this.entry = entry;
this.text = new StringBuilder(String.valueOf(entry.value));
this.cursor = text.length();
}
}
private static class TerminalInput implements AutoCloseable {
private static final String POWERSHELL_SCRIPT =
"$ErrorActionPreference='Stop'; "
+ "[Console]::TreatControlCAsInput=$true; "
+ "while($true){$key=[Console]::ReadKey($true);$code=0;"
+ "switch($key.Key.ToString()){"
+ "'UpArrow'{$code=1114112}'DownArrow'{$code=1114113}"
+ "'LeftArrow'{$code=1114114}'RightArrow'{$code=1114115}"
+ "'Home'{$code=1114116}'End'{$code=1114117}"
+ "'Delete'{$code=1114118}'Enter'{$code=13}"
+ "'Backspace'{$code=8}'Escape'{$code=27}};"
+ "if (($key.Modifiers -band [ConsoleModifiers]::Control) -ne 0 "
+ "-and $key.Key -eq [ConsoleKey]::A){$code=1114119};"
+ "if (($key.Modifiers -band [ConsoleModifiers]::Control) -ne 0 "
+ "-and $key.Key -eq [ConsoleKey]::C){$code=3};"
+ "if ($code -eq 0 -and $key.KeyChar -ne [char]0 "
+ "-and -not [char]::IsControl($key.KeyChar)) {$code=[int]$key.KeyChar};"
+ "if ($code -ne 0) {[Console]::Out.WriteLine($code);[Console]::Out.Flush()};"
+ "if ($code -eq 3) {break}}";
private final Process process;
private final BufferedReader reader;
private TerminalInput(Process process) {
this.process = process;
this.reader = new BufferedReader(
new InputStreamReader(process.getInputStream(), StandardCharsets.US_ASCII));
}
static TerminalInput start() throws IOException {
ProcessBuilder builder = new ProcessBuilder(
"powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive",
"-Command", POWERSHELL_SCRIPT);
builder.redirectInput(ProcessBuilder.Redirect.INHERIT);
builder.redirectError(ProcessBuilder.Redirect.INHERIT);
return new TerminalInput(builder.start());
}
int readKey() throws IOException {
String code = reader.readLine();
if (code == null) {
throw new IOException("PowerShell stopped reading terminal input.");
}
return Integer.parseInt(code);
}
@Override
public void close() throws IOException {
process.destroy();
reader.close();
}
}
}