1 /* 2 * Copyright (C) 2020 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.systemui.util 18 19 import android.graphics.Rect 20 import android.util.IndentingPrintWriter 21 import android.view.View 22 import android.view.ViewGroup 23 import java.io.PrintWriter 24 25 /** [Sequence] that yields all of the direct children of this [ViewGroup] */ 26 val ViewGroup.children <lambda>null27 get() = sequence { for (i in 0 until childCount) yield(getChildAt(i)) } 28 29 /** Inclusive version of [Iterable.takeWhile] */ <lambda>null30fun <T> Sequence<T>.takeUntil(pred: (T) -> Boolean): Sequence<T> = sequence { 31 for (x in this@takeUntil) { 32 yield(x) 33 if (pred(x)) { 34 break 35 } 36 } 37 } 38 39 /** 40 * If `this` is an [IndentingPrintWriter], it will process block inside an indentation level. 41 * 42 * If not, this will just process block. 43 */ indentIfPossiblenull44inline fun PrintWriter.indentIfPossible(block: PrintWriter.() -> Unit) { 45 if (this is IndentingPrintWriter) increaseIndent() 46 block() 47 if (this is IndentingPrintWriter) decreaseIndent() 48 } 49 50 /** Convenience extension property for [View.getBoundsOnScreen]. */ 51 val View.boundsOnScreen: Rect 52 get() { 53 val bounds = Rect() 54 getBoundsOnScreen(bounds) 55 return bounds 56 } 57 58 /** 59 * Returns whether this [Collection] contains exactly all [elements]. 60 * 61 * Order of elements is not taken into account, but multiplicity is. For example, an element 62 * duplicated exactly 3 times in the parameter asserts that the element must likewise be duplicated 63 * exactly 3 times in this [Collection]. 64 */ containsExactlynull65fun <T> Collection<T>.containsExactly(vararg elements: T): Boolean { 66 return eachCountMap() == elements.asList().eachCountMap() 67 } 68 69 /** 70 * Returns a map where keys are the distinct elements of the collection and values are their 71 * corresponding counts. 72 * 73 * This is a convenient extension function for any [Collection] that allows you to easily count the 74 * occurrences of each element. 75 */ eachCountMapnull76fun <T> Collection<T>.eachCountMap(): Map<T, Int> { 77 return groupingBy { it }.eachCount() 78 } 79