Repository navigation
Expand file tree
/
Copy pathPrintAnsi.java
More file actions
executable file
·57 lines (53 loc) · 2.13 KB
/
Copy pathPrintAnsi.java
File metadata and controls
executable file
·57 lines (53 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS org.codejive.miniterm:miniterm${miniterm.ffm:}:${miniterm.version:0.2.0}
//DEPS org.codejive.miniterm:ansiparser:${miniterm.version:0.2.0}
package examples;
import java.io.IOException;
import org.codejive.miniterm.Terminal;
import org.codejive.miniterm.ansiparser.AnsiReader;
public class PrintAnsi {
public static void main(String[] args) {
try (Terminal terminal = Terminal.create()) {
terminal.enableRawMode();
System.out.println("Press keys (Ctrl+C to exit):");
AnsiReader reader = new AnsiReader(() -> terminal.read(-1));
String token;
while ((token = reader.read()) != null) {
if (token.isEmpty()) {
System.out.println("Timeout");
continue;
} else if (token.startsWith("\u001b")) {
if (token.equals("\u001b[A")) {
System.out.println("Up arrow");
} else if (token.equals("\u001b[B")) {
System.out.println("Down arrow");
} else if (token.equals("\u001b[C")) {
System.out.println("Right arrow");
} else if (token.equals("\u001b[D")) {
System.out.println("Left arrow");
} else {
System.out.println("Sequence: " + toHex(token));
}
} else if (token.charAt(0) == 3) {
System.out.println("CTRL+C pressed: exiting...");
break; // Ctrl+C
} else {
System.out.println("Key pressed: " + token);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static String toHex(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (c >= 0x20 && c < 0x7f) {
sb.append(c);
} else {
sb.append(String.format("\\x%02x", (int) c));
}
}
return sb.toString();
}
}