1 /*
2  * Copyright (C) 2021 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.wallpaper.util
17 
18 import android.content.Context
19 import android.graphics.Point
20 import android.hardware.display.DisplayManager
21 import android.util.Log
22 import android.view.Display
23 
24 /**
25  * Utility class to provide methods to find and obtain information about displays via
26  * {@link DisplayManager}
27  */
28 class DisplayUtils(context: Context) {
29     companion object {
30         private const val TAG = "DisplayUtils"
31     }
32 
33     private val internalDisplays: List<Display>
34 
35     init {
36         val appContext = context.applicationContext
37         val dm = appContext.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
38         val allDisplays: Array<out Display> = dm.displays
39         if (allDisplays.isEmpty()) {
40             Log.e(TAG, "No displays found on context $appContext")
41             throw RuntimeException("No displays found!")
42         }
43         internalDisplays = allDisplays.filter { it.type == Display.TYPE_INTERNAL }
44     }
45 
46     /**
47      * Returns the {@link Display} to be used to calculate wallpaper size and cropping.
48      */
49     fun getWallpaperDisplay(): Display {
50         return internalDisplays.maxWithOrNull { a, b -> getRealSize(a) - getRealSize(b) }
51                 ?: internalDisplays[0]
52     }
53 
54     private fun getRealSize(display: Display): Int {
55         val p = Point()
56         display.getRealSize(p)
57         return p.x * p.y
58     }
59 }
60