1 /* 2 * Copyright (C) 2012 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.inputmethod.keyboard.tools; 18 19 import java.io.PrintStream; 20 21 public class ArrayInitializerFormatter { 22 private final PrintStream mOut; 23 private final int mMaxWidth; 24 private final String mIndent; 25 26 private int mCurrentIndex = 0; 27 private String mFixedElement; 28 private final StringBuilder mBuffer = new StringBuilder(); 29 private int mBufferedLen; 30 private int mBufferedIndex = Integer.MIN_VALUE; 31 32 public ArrayInitializerFormatter(PrintStream out, int width, String indent) { 33 mOut = out; 34 mMaxWidth = width - indent.length(); 35 mIndent = indent; 36 } 37 38 public void flush() { 39 if (mBuffer.length() == 0) { 40 return; 41 } 42 final int lastIndex = mCurrentIndex - 1; 43 if (mBufferedIndex == lastIndex) { 44 mOut.format("%s/* %d */ %s\n", mIndent, mBufferedIndex, mBuffer); 45 } else if (mBufferedIndex == lastIndex - 1) { 46 final String[] elements = mBuffer.toString().split(" "); 47 mOut.format("%s/* %d */ %s\n" 48 + "%s/* %d */ %s\n", 49 mIndent, mBufferedIndex, elements[0], 50 mIndent, lastIndex, elements[1]); 51 } else { 52 mOut.format("%s/* %d~ */\n" 53 + "%s%s\n" 54 + "%s/* ~%d */\n", mIndent, mBufferedIndex, 55 mIndent, mBuffer, 56 mIndent, lastIndex); 57 } 58 mBuffer.setLength(0); 59 mBufferedLen = 0; 60 } 61 62 public void outCommentLines(String lines) { 63 flush(); 64 mOut.print(lines); 65 mFixedElement = null; 66 } 67 68 public void outElement(String element) { 69 if (!element.equals(mFixedElement)) { 70 flush(); 71 mBufferedIndex = mCurrentIndex; 72 } 73 final int nextLen = mBufferedLen + " ".length() + element.length(); 74 if (mBufferedLen != 0 && nextLen < mMaxWidth) { 75 mBuffer.append(' '); 76 mBuffer.append(element); 77 mBufferedLen = nextLen; 78 } else { 79 if (mBufferedLen != 0) { 80 mBuffer.append('\n'); 81 mBuffer.append(mIndent); 82 } 83 mBuffer.append(element); 84 mBufferedLen = element.length(); 85 } 86 mCurrentIndex++; 87 mFixedElement = element; 88 } 89 } 90