1 /* <lambda>null2 * 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.settings.print 18 19 import android.content.Context 20 import android.graphics.drawable.Drawable 21 import android.print.PrintManager 22 import android.printservice.PrintServiceInfo 23 import com.android.settings.R 24 import com.android.settingslib.spa.framework.util.mapItem 25 import kotlinx.coroutines.Dispatchers 26 import kotlinx.coroutines.channels.awaitClose 27 import kotlinx.coroutines.flow.Flow 28 import kotlinx.coroutines.flow.callbackFlow 29 import kotlinx.coroutines.flow.conflate 30 import kotlinx.coroutines.flow.flowOn 31 import kotlinx.coroutines.flow.map 32 33 class PrintRepository(private val context: Context) { 34 35 private val printManager = context.getSystemService(PrintManager::class.java)!! 36 private val packageManager = context.packageManager 37 38 data class PrintServiceDisplayInfo( 39 val title: String, 40 val isEnabled: Boolean, 41 val summary: String, 42 val icon: Drawable, 43 val componentName: String, 44 ) 45 46 fun printServiceDisplayInfosFlow(): Flow<List<PrintServiceDisplayInfo>> = 47 printServicesFlow() 48 .mapItem { printService -> printService.toPrintServiceDisplayInfo() } 49 .conflate() 50 .flowOn(Dispatchers.Default) 51 52 private fun PrintServiceInfo.toPrintServiceDisplayInfo() = PrintServiceDisplayInfo( 53 title = resolveInfo.loadLabel(packageManager).toString(), 54 isEnabled = isEnabled, 55 summary = context.getString( 56 if (isEnabled) R.string.print_feature_state_on else R.string.print_feature_state_off 57 ), 58 icon = resolveInfo.loadIcon(packageManager), 59 componentName = componentName.flattenToString(), 60 ) 61 62 private fun printServicesFlow(): Flow<List<PrintServiceInfo>> = 63 printManager.printServicesChangeFlow() 64 .map { printManager.getPrintServices(PrintManager.ALL_SERVICES) } 65 .conflate() 66 .flowOn(Dispatchers.Default) 67 68 private companion object { 69 fun PrintManager.printServicesChangeFlow(): Flow<Unit> = callbackFlow { 70 val listener = PrintManager.PrintServicesChangeListener { trySend(Unit) } 71 addPrintServicesChangeListener(listener, null) 72 trySend(Unit) 73 awaitClose { removePrintServicesChangeListener(listener) } 74 }.conflate().flowOn(Dispatchers.Default) 75 } 76 } 77