1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.xsdc; 18 19 import java.io.Closeable; 20 import java.io.PrintWriter; 21 22 public class CodeWriter implements Closeable { 23 private PrintWriter out; 24 private int indent; 25 private boolean startLine; 26 CodeWriter()27 public CodeWriter() { 28 this(null); 29 } 30 CodeWriter(PrintWriter printWriter)31 public CodeWriter(PrintWriter printWriter) { 32 out = printWriter; 33 indent = 0; 34 startLine = true; 35 } 36 printIndent()37 private void printIndent() { 38 assert startLine; 39 for (int i = 0; i < indent; ++i) { 40 printImpl(" "); 41 } 42 startLine = false; 43 } 44 println()45 public void println() { 46 if (out != null) { 47 out.println(); 48 } 49 startLine = true; 50 } 51 println(String code)52 public void println(String code) { 53 print(code + "\n"); 54 } 55 print(String code)56 public void print(String code) { 57 String[] lines = code.split("\n", -1); 58 for (int i = 0; i < lines.length; ++i) { 59 // trim only start of line for more flexibility 60 String line = lines[i].replaceAll("^\\s+", ""); 61 if (line.startsWith("}")) { 62 --indent; 63 } 64 if (startLine && !line.isEmpty()) { 65 printIndent(); 66 } 67 printImpl(line); 68 if (line.endsWith("{")) { 69 ++indent; 70 } 71 if (i + 1 < lines.length) { 72 println(); 73 } 74 } 75 } 76 printf(String code, Object... arguments)77 public void printf(String code, Object... arguments) { 78 print(String.format(code, arguments)); 79 } 80 81 @Override close()82 public void close() { 83 if (out != null) { 84 out.close(); 85 } 86 } 87 printImpl(String code)88 private void printImpl(String code) { 89 if (out != null) { 90 out.print(code); 91 } 92 } 93 } 94