1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.jline;
20
21 import java.util.function.Consumer;
22
23 import org.apache.maven.api.services.MessageBuilder;
24 import org.apache.maven.api.services.MessageBuilderFactory;
25 import org.jline.jansi.AnsiConsole;
26 import org.jline.reader.LineReader;
27 import org.jline.reader.LineReaderBuilder;
28 import org.jline.terminal.Terminal;
29 import org.jline.terminal.TerminalBuilder;
30
31 public class MessageUtils {
32
33 static Terminal terminal;
34 static LineReader reader;
35 static MessageBuilderFactory messageBuilderFactory = new JLineMessageBuilderFactory();
36 static boolean colorEnabled = true;
37 static Thread shutdownHook;
38 static final Object STARTUP_SHUTDOWN_MONITOR = new Object();
39
40 public static void systemInstall(Terminal terminal) {
41 MessageUtils.terminal = terminal;
42 MessageUtils.reader = createReader(terminal);
43 }
44
45 public static void systemInstall() {
46 systemInstall(null, null);
47 }
48
49 public static void systemInstall(Consumer<TerminalBuilder> builderConsumer, Consumer<Terminal> terminalConsumer) {
50 MessageUtils.terminal = new FastTerminal(
51 () -> {
52 TerminalBuilder builder =
53 TerminalBuilder.builder().name("Maven").dumb(true);
54 if (builderConsumer != null) {
55 builderConsumer.accept(builder);
56 }
57 return builder.build();
58 },
59 terminal -> {
60 MessageUtils.reader = createReader(terminal);
61 AnsiConsole.setTerminal(terminal);
62 AnsiConsole.systemInstall();
63 if (terminalConsumer != null) {
64 terminalConsumer.accept(terminal);
65 }
66 });
67 }
68
69 private static LineReader createReader(Terminal terminal) {
70 return LineReaderBuilder.builder().terminal(terminal).build();
71 }
72
73 public static void registerShutdownHook() {
74 if (shutdownHook == null) {
75 shutdownHook = new Thread(() -> {
76 synchronized (MessageUtils.STARTUP_SHUTDOWN_MONITOR) {
77 MessageUtils.doSystemUninstall();
78 }
79 });
80 Runtime.getRuntime().addShutdownHook(shutdownHook);
81 }
82 }
83
84 public static void systemUninstall() {
85 doSystemUninstall();
86 if (shutdownHook != null) {
87 try {
88 Runtime.getRuntime().removeShutdownHook(shutdownHook);
89 } catch (IllegalStateException var3) {
90
91 }
92 }
93 }
94
95 private static void doSystemUninstall() {
96 try {
97 AnsiConsole.systemUninstall();
98 } finally {
99 terminal = null;
100 }
101 }
102
103 public static void setColorEnabled(boolean enabled) {
104 colorEnabled = enabled;
105 }
106
107 public static boolean isColorEnabled() {
108 return colorEnabled && terminal != null;
109 }
110
111 public static int getTerminalWidth() {
112 return terminal != null ? terminal.getWidth() : -1;
113 }
114
115 public static MessageBuilder builder() {
116 return messageBuilderFactory.builder();
117 }
118
119 public static Terminal getTerminal() {
120 return terminal;
121 }
122 }