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