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;
21
22/**
23 * Lightweight wrapper around {@link PrintWriter} that automatically indents
24 * newlines based on internal state. Delays writing indent until first actual
25 * write on a newline, enabling indent modification after newline.
26 */
27public class IndentingPrintWriter extends PrintWriter {
28    private final String mIndent;
29
30    private StringBuilder mBuilder = new StringBuilder();
31    private String mCurrent = new String();
32    private boolean mEmptyLine = true;
33
34    public IndentingPrintWriter(Writer writer, String indent) {
35        super(writer);
36        mIndent = indent;
37    }
38
39    public void increaseIndent() {
40        mBuilder.append(mIndent);
41        mCurrent = mBuilder.toString();
42    }
43
44    public void decreaseIndent() {
45        mBuilder.delete(0, mIndent.length());
46        mCurrent = mBuilder.toString();
47    }
48
49    public void printPair(String key, Object value) {
50        print(key + "=" + String.valueOf(value) + " ");
51    }
52
53    @Override
54    public void println() {
55        super.println();
56        mEmptyLine = true;
57    }
58
59    @Override
60    public void write(char[] buf, int offset, int count) {
61        if (mEmptyLine) {
62            mEmptyLine = false;
63            super.print(mCurrent);
64        }
65        super.write(buf, offset, count);
66    }
67}
68