1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 * except in compliance with the License. You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software distributed under the 10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 11 * KIND, either express or implied. See the License for the specific language governing 12 * permissions and limitations under the License. 13 */ 14 package com.android.systemui.plugins.processor 15 16 import java.io.BufferedWriter 17 import java.io.Writer 18 19 /** 20 * [TabbedWriter] is a convience class which tracks and writes correctly tabbed lines for generating 21 * source files. These files don't need to be correctly tabbed as they're ephemeral and not part of 22 * the source tree, but correct tabbing makes debugging much easier when the build fails. 23 */ 24 class TabbedWriter(writer: Writer) : AutoCloseable { 25 private val target = BufferedWriter(writer) 26 private var isInProgress = false 27 var tabCount: Int = 0 28 private set 29 closenull30 override fun close() = target.close() 31 32 fun line() { 33 target.newLine() 34 isInProgress = false 35 } 36 linenull37 fun line(str: String) { 38 if (isInProgress) { 39 target.newLine() 40 } 41 42 target.append(" ".repeat(tabCount)) 43 target.append(str) 44 target.newLine() 45 isInProgress = false 46 } 47 completeLinenull48 fun completeLine(str: String) { 49 if (!isInProgress) { 50 target.newLine() 51 target.append(" ".repeat(tabCount)) 52 } 53 54 target.append(str) 55 target.newLine() 56 isInProgress = false 57 } 58 startLinenull59 fun startLine(str: String) { 60 if (isInProgress) { 61 target.newLine() 62 } 63 64 target.append(" ".repeat(tabCount)) 65 target.append(str) 66 isInProgress = true 67 } 68 appendLinenull69 fun appendLine(str: String) { 70 if (!isInProgress) { 71 target.append(" ".repeat(tabCount)) 72 } 73 74 target.append(str) 75 isInProgress = true 76 } 77 braceBlocknull78 fun braceBlock(str: String = "", write: TabbedWriter.() -> Unit) { 79 block(str, " {", "}", true, write) 80 } 81 parenBlocknull82 fun parenBlock(str: String = "", write: TabbedWriter.() -> Unit) { 83 block(str, "(", ")", false, write) 84 } 85 blocknull86 private fun block( 87 str: String, 88 start: String, 89 end: String, 90 newLineForEnd: Boolean, 91 write: TabbedWriter.() -> Unit, 92 ) { 93 appendLine(str) 94 completeLine(start) 95 96 tabCount++ 97 this.write() 98 tabCount-- 99 100 if (newLineForEnd) { 101 line(end) 102 } else { 103 startLine(end) 104 } 105 } 106 107 companion object { writeTonull108 fun writeTo(writer: Writer, write: TabbedWriter.() -> Unit) { 109 TabbedWriter(writer).use { it.write() } 110 } 111 } 112 } 113