/
ConsoleStream.java
59 lines (49 loc) · 1.85 KB
/
ConsoleStream.java
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
58
59
package net.ME1312.Galaxi.Engine.Library.Log;
import net.ME1312.Galaxi.Library.Container.Container;
import net.ME1312.Galaxi.Library.Log.StringOutputStream;
import net.ME1312.Galaxi.Library.Util;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.AnsiString;
import org.jline.reader.LineReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import static net.ME1312.Galaxi.Engine.GalaxiOption.USE_ANSI;
/**
* Console Log Stream Class
*/
public class ConsoleStream extends StringOutputStream {
private Container<OutputStream> window;
private LineReader jline;
private StringBuilder buffer;
ConsoleStream(Container<OutputStream> window, LineReader jline) {
this.window = window;
this.jline = jline;
this.buffer = new StringBuilder();
}
@Override
public void write(String s) {
try {
OutputStream window;
if ((window = this.window.get()) != null) {
Util.isException(() -> window.write(s.getBytes(StandardCharsets.UTF_8)));
}
if (s.contains("\n")) {
StringBuilder buffer = this.buffer;
this.buffer = new StringBuilder();
int i = s.lastIndexOf("\n") + 1;
if (i < s.length()) {
buffer.append(s, 0, i);
this.buffer.append(s.substring(i));
} else {
buffer.append(s);
}
if (USE_ANSI.def()) {
jline.printAbove(buffer.toString().replace("\n", Ansi.ansi().a(Ansi.Attribute.RESET) + "\n"));
} else jline.printAbove((String) new AnsiString(buffer.toString()).getPlain());
jline.getTerminal().flush();
} else {
buffer.append(s);
}
} catch (Exception e) {}
}
}