• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2024 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.qs.panels.shared.model
18 
19 /** Represents a tile of type [T] associated with a width */
20 interface SizedTile<T> {
21     val tile: T
22     val width: Int
23     val isIcon: Boolean
24         get() = width == 1
25 }
26 
27 data class SizedTileImpl<T>(
28     override val tile: T,
29     override val width: Int,
30 ) : SizedTile<T>
31 
32 /** Represents a row of [SizedTile] with a maximum width of [columns] */
33 class TileRow<T>(private val columns: Int) {
34     private var availableColumns = columns
35     private val _tiles: MutableList<SizedTile<T>> = mutableListOf()
36     val tiles: List<SizedTile<T>>
37         get() = _tiles.toList()
38 
maybeAddTilenull39     fun maybeAddTile(tile: SizedTile<T>): Boolean {
40         if (availableColumns - tile.width >= 0) {
41             _tiles.add(tile)
42             availableColumns -= tile.width
43             return true
44         }
45         return false
46     }
47 
findLastIconTilenull48     fun findLastIconTile(): SizedTile<T>? {
49         return _tiles.findLast { it.width == 1 }
50     }
51 
removeTilenull52     fun removeTile(tile: SizedTile<T>) {
53         _tiles.remove(tile)
54         availableColumns += tile.width
55     }
56 
clearnull57     fun clear() {
58         _tiles.clear()
59         availableColumns = columns
60     }
61 
isFullnull62     fun isFull(): Boolean = availableColumns == 0
63 }
64 
65 /**
66  * Converts a list of [SizedTile] to a sequence of rows based on the number of columns of the grid
67  */
68 fun <T> splitInRowsSequence(
69     tiles: List<SizedTile<T>>,
70     columns: Int,
71 ): Sequence<List<SizedTile<T>>> = sequence {
72     val row = TileRow<T>(columns)
73     for (tile in tiles) {
74         check(tile.width <= columns)
75         if (!row.maybeAddTile(tile)) {
76             // Couldn't add tile to previous row, create a row with the current tiles
77             // and start a new one
78             yield(row.tiles)
79             row.clear()
80             row.maybeAddTile(tile)
81         }
82     }
83     if (row.tiles.isNotEmpty()) {
84         yield(row.tiles)
85     }
86 }
87