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
17package com.android.internal.util;
18
19import java.io.PrintWriter;
20import java.io.Writer;
21import java.util.Arrays;
22
23/**
24 * Lightweight wrapper around {@link PrintWriter} that automatically indents
25 * newlines based on internal state. It also automatically wraps long lines
26 * based on given line length.
27 * <p>
28 * Delays writing indent until first actual write on a newline, enabling indent
29 * modification after newline.
30 */
31public class IndentingPrintWriter extends PrintWriter {
32    private final String mSingleIndent;
33    private final int mWrapLength;
34
35    /** Mutable version of current indent */
36    private StringBuilder mIndentBuilder = new StringBuilder();
37    /** Cache of current {@link #mIndentBuilder} value */
38    private char[] mCurrentIndent;
39    /** Length of current line being built, excluding any indent */
40    private int mCurrentLength;
41
42    /**
43     * Flag indicating if we're currently sitting on an empty line, and that
44     * next write should be prefixed with the current indent.
45     */
46    private boolean mEmptyLine = true;
47
48    private char[] mSingleChar = new char[1];
49
50    public IndentingPrintWriter(Writer writer, String singleIndent) {
51        this(writer, singleIndent, -1);
52    }
53
54    public IndentingPrintWriter(Writer writer, String singleIndent, int wrapLength) {
55        super(writer);
56        mSingleIndent = singleIndent;
57        mWrapLength = wrapLength;
58    }
59
60    public void increaseIndent() {
61        mIndentBuilder.append(mSingleIndent);
62        mCurrentIndent = null;
63    }
64
65    public void decreaseIndent() {
66        mIndentBuilder.delete(0, mSingleIndent.length());
67        mCurrentIndent = null;
68    }
69
70    public void printPair(String key, Object value) {
71        print(key + "=" + String.valueOf(value) + " ");
72    }
73
74    public void printPair(String key, Object[] value) {
75        print(key + "=" + Arrays.toString(value) + " ");
76    }
77
78    public void printHexPair(String key, int value) {
79        print(key + "=0x" + Integer.toHexString(value) + " ");
80    }
81
82    @Override
83    public void println() {
84        write('\n');
85    }
86
87    @Override
88    public void write(int c) {
89        mSingleChar[0] = (char) c;
90        write(mSingleChar, 0, 1);
91    }
92
93    @Override
94    public void write(String s, int off, int len) {
95        final char[] buf = new char[len];
96        s.getChars(off, len - off, buf, 0);
97        write(buf, 0, len);
98    }
99
100    @Override
101    public void write(char[] buf, int offset, int count) {
102        final int indentLength = mIndentBuilder.length();
103        final int bufferEnd = offset + count;
104        int lineStart = offset;
105        int lineEnd = offset;
106
107        // March through incoming buffer looking for newlines
108        while (lineEnd < bufferEnd) {
109            char ch = buf[lineEnd++];
110            mCurrentLength++;
111            if (ch == '\n') {
112                maybeWriteIndent();
113                super.write(buf, lineStart, lineEnd - lineStart);
114                lineStart = lineEnd;
115                mEmptyLine = true;
116                mCurrentLength = 0;
117            }
118
119            // Wrap if we've pushed beyond line length
120            if (mWrapLength > 0 && mCurrentLength >= mWrapLength - indentLength) {
121                if (!mEmptyLine) {
122                    // Give ourselves a fresh line to work with
123                    super.write('\n');
124                    mEmptyLine = true;
125                    mCurrentLength = lineEnd - lineStart;
126                } else {
127                    // We need more than a dedicated line, slice it hard
128                    maybeWriteIndent();
129                    super.write(buf, lineStart, lineEnd - lineStart);
130                    super.write('\n');
131                    mEmptyLine = true;
132                    lineStart = lineEnd;
133                    mCurrentLength = 0;
134                }
135            }
136        }
137
138        if (lineStart != lineEnd) {
139            maybeWriteIndent();
140            super.write(buf, lineStart, lineEnd - lineStart);
141        }
142    }
143
144    private void maybeWriteIndent() {
145        if (mEmptyLine) {
146            mEmptyLine = false;
147            if (mIndentBuilder.length() != 0) {
148                if (mCurrentIndent == null) {
149                    mCurrentIndent = mIndentBuilder.toString().toCharArray();
150                }
151                super.write(mCurrentIndent, 0, mCurrentIndent.length);
152            }
153        }
154    }
155}
156