1 /*
2  * Copyright 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 package com.android.photopicker.core.theme
17 
18 import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
19 import androidx.compose.material3.windowsizeclass.WindowSizeClass
20 import androidx.compose.runtime.Composable
21 import androidx.compose.runtime.staticCompositionLocalOf
22 import androidx.compose.ui.graphics.toComposeRect
23 import androidx.compose.ui.platform.LocalContext
24 import androidx.compose.ui.platform.LocalDensity
25 import androidx.window.layout.WindowMetricsCalculator
26 import com.android.photopicker.core.configuration.LocalPhotopickerConfiguration
27 
28 /**
29  * Provider for the [WindowSizeClass] inside of composables. A [staticCompositionLocalOf] is used
30  * here, due to the nature of WindowSizes; if the WindowSize is changing, recomposition is
31  * unavoidable so there is no sense in keeping track of references that use this value.
32  */
33 val LocalWindowSizeClass =
<lambda>null34     staticCompositionLocalOf<WindowSizeClass> {
35         throw IllegalStateException(
36             "No WindowSizeClass configured. Make sure to use LocalWindowSizeClass in a Composable" +
37                 " surrounded by a PhotopickerTheme {}."
38         )
39     }
40 
41 /**
42  * Helper function which calculates a WindowSizeClass incorporating the window rect and
43  * [LocalDensity].
44  *
45  * Note: This method observes [LocalPhotopickerConfiguration] and requires that to be provided
46  * higher in the tree.
47  */
48 @OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
49 @Composable
calculateWindowSizeClassnull50 fun calculateWindowSizeClass(): WindowSizeClass {
51 
52     // Observe PhotopickerConfiguration changes and recalculate the size class on each change.
53     LocalPhotopickerConfiguration.current
54 
55     val context = LocalContext.current
56     val density = LocalDensity.current
57     val metrics = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(context)
58     val size = with(density) { metrics.bounds.toComposeRect().size.toDpSize() }
59     return WindowSizeClass.calculateFromSize(size)
60 }
61