View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.jline;
20  
21  import javax.inject.Named;
22  import javax.inject.Singleton;
23  
24  import java.util.Arrays;
25  import java.util.List;
26  import java.util.Locale;
27  import java.util.Map;
28  import java.util.TreeSet;
29  import java.util.concurrent.ConcurrentHashMap;
30  
31  import org.apache.maven.api.services.MessageBuilder;
32  import org.apache.maven.api.services.MessageBuilderFactory;
33  import org.eclipse.sisu.Priority;
34  
35  /**
36   * Message builder factory emitting ANSI colors. The class name is kept for compatibility, JLine is not used anymore.
37   */
38  @Named
39  @Singleton
40  @Priority(10)
41  public class JLineMessageBuilderFactory implements MessageBuilderFactory {
42  
43      static final String RESET = "\u001B[0m";
44  
45      private static final List<String> COLORS =
46              Arrays.asList("black", "red", "green", "yellow", "blue", "magenta", "cyan", "white");
47  
48      private static final Map<String, String> STYLES = new ConcurrentHashMap<>();
49  
50      @Override
51      public boolean isColorEnabled() {
52          return MessageUtils.isColorEnabled();
53      }
54  
55      @Override
56      public int getTerminalWidth() {
57          return MessageUtils.getTerminalWidth();
58      }
59  
60      @Override
61      public MessageBuilder builder() {
62          return builder(64);
63      }
64  
65      @Override
66      public MessageBuilder builder(int size) {
67          return new AnsiMessageBuilder(size);
68      }
69  
70      /**
71       * Resolves a style to its ANSI escape sequence (empty if it has no effect). A style is either a spec like
72       * {@code bold,f:red}, or a reference {@code .name:-default} looked up from the {@code maven.style.name} or
73       * {@code style.name} system property, falling back to {@code default}.
74       */
75      static String resolve(String style) {
76          return STYLES.computeIfAbsent(style, JLineMessageBuilderFactory::doResolve);
77      }
78  
79      private static String doResolve(String style) {
80          String spec = style;
81          if (spec.startsWith(".")) {
82              int i = spec.indexOf(":-");
83              String name = i < 0 ? spec.substring(1) : spec.substring(1, i);
84              String def = i < 0 ? "" : spec.substring(i + 2);
85              spec = System.getProperty("maven.style." + name, System.getProperty("style." + name, def));
86          }
87          // same order as JLine emitted (ITs match exact bytes): attributes 3-9, foreground, background, bold, faint
88          String[] slots = new String[5];
89          TreeSet<String> attributes = new TreeSet<>();
90          for (String item : spec.split(",")) {
91              String code = code(item.trim().toLowerCase(Locale.ROOT));
92              if (code == null) {
93                  continue;
94              }
95              int colon = item.trim().indexOf(':');
96              if (colon > 0) {
97                  String target = item.trim().substring(0, colon).toLowerCase(Locale.ROOT);
98                  slots[target.startsWith("f") ? 1 : 2] = code;
99              } else if (code.equals("1")) {
100                 slots[3] = code;
101             } else if (code.equals("2")) {
102                 slots[4] = code;
103             } else {
104                 attributes.add(code);
105             }
106         }
107         slots[0] = attributes.isEmpty() ? null : String.join(";", attributes);
108         StringBuilder codes = new StringBuilder();
109         for (String slot : slots) {
110             if (slot != null) {
111                 codes.append(codes.length() > 0 ? ";" : "").append(slot);
112             }
113         }
114         return codes.length() > 0 ? "\u001B[" + codes + "m" : "";
115     }
116 
117     // ponytail: the subset of JLine's style syntax Maven styles use; unknown items are ignored
118     private static String code(String item) {
119         switch (item) {
120             case "bold":
121                 return "1";
122             case "faint":
123                 return "2";
124             case "italic":
125                 return "3";
126             case "underline":
127                 return "4";
128             case "blink":
129                 return "5";
130             case "inverse":
131                 return "7";
132             case "conceal":
133             case "hidden":
134                 return "8";
135             case "crossed-out":
136                 return "9";
137             default:
138         }
139         int colon = item.indexOf(':');
140         if (colon < 0) {
141             return null;
142         }
143         String target = item.substring(0, colon);
144         boolean fg = target.equals("f") || target.equals("fg") || target.equals("foreground");
145         boolean bg = target.equals("b") || target.equals("bg") || target.equals("background");
146         return fg || bg ? color(item.substring(colon + 1), fg) : null;
147     }
148 
149     private static String color(String color, boolean fg) {
150         if (color.equals("default")) {
151             return fg ? "39" : "49";
152         }
153         boolean bright = false;
154         if (color.startsWith("bright-")) {
155             bright = true;
156             color = color.substring("bright-".length());
157         } else if (color.startsWith("!")) {
158             bright = true;
159             color = color.substring(1);
160         }
161         int index = COLORS.indexOf(color);
162         if (index >= 0) {
163             return String.valueOf((fg ? 30 : 40) + (bright ? 60 : 0) + index);
164         }
165         try {
166             if (color.startsWith("#") || color.startsWith("x")) {
167                 int rgb = Integer.parseInt(color.substring(1), 16);
168                 return (fg ? "38" : "48") + ";2;" + (rgb >> 16 & 0xff) + ";" + (rgb >> 8 & 0xff) + ";" + (rgb & 0xff);
169             }
170             return (fg ? "38" : "48") + ";5;" + (Integer.parseInt(color) & 0xff);
171         } catch (NumberFormatException e) {
172             return null;
173         }
174     }
175 
176     private static class AnsiMessageBuilder implements MessageBuilder {
177         private final StringBuilder builder;
178         private boolean styled;
179 
180         private AnsiMessageBuilder(int size) {
181             this.builder = new StringBuilder(size);
182         }
183 
184         @Override
185         public MessageBuilder style(String style) {
186             if (MessageUtils.isColorEnabled()) {
187                 String ansi = resolve(style);
188                 if (!ansi.isEmpty()) {
189                     if (styled) {
190                         builder.append(RESET);
191                     }
192                     builder.append(ansi);
193                     styled = true;
194                 }
195             }
196             return this;
197         }
198 
199         @Override
200         public MessageBuilder resetStyle() {
201             if (styled) {
202                 builder.append(RESET);
203                 styled = false;
204             }
205             return this;
206         }
207 
208         @Override
209         public MessageBuilder append(CharSequence cs) {
210             builder.append(cs);
211             return this;
212         }
213 
214         @Override
215         public MessageBuilder append(CharSequence cs, int start, int end) {
216             builder.append(cs, start, end);
217             return this;
218         }
219 
220         @Override
221         public MessageBuilder append(char c) {
222             builder.append(c);
223             return this;
224         }
225 
226         @Override
227         public MessageBuilder setLength(int length) {
228             builder.setLength(length);
229             if (length == 0) {
230                 styled = false;
231             }
232             return this;
233         }
234 
235         @Override
236         public String build() {
237             return styled ? builder + RESET : builder.toString();
238         }
239 
240         @Override
241         public String toString() {
242             return build();
243         }
244     }
245 }