1 /*
2  * Copyright (C) 2022 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.settingslib.spa.slice
18 
19 import android.net.Uri
20 import android.util.Log
21 import com.android.settingslib.spa.framework.common.EntrySliceData
22 import com.android.settingslib.spa.framework.common.SettingsEntryRepository
23 import com.android.settingslib.spa.framework.util.getEntryId
24 
25 private const val TAG = "SliceDataRepository"
26 
27 class SettingsSliceDataRepository(private val entryRepository: SettingsEntryRepository) {
28     // The map of slice uri to its EntrySliceData, a.k.a. LiveData<Slice?>
29     private val sliceDataMap: MutableMap<String, EntrySliceData> = mutableMapOf()
30 
31     // Note: mark this function synchronized, so that we can get the same livedata during the
32     // whole lifecycle of a Slice.
33     @Synchronized
getOrBuildSliceDatanull34     fun getOrBuildSliceData(sliceUri: Uri): EntrySliceData? {
35         val sliceString = sliceUri.getSliceId() ?: return null
36         return sliceDataMap[sliceString] ?: buildLiveDataImpl(sliceUri)?.let {
37             sliceDataMap[sliceString] = it
38             it
39         }
40     }
41 
getActiveSliceDatanull42     fun getActiveSliceData(sliceUri: Uri): EntrySliceData? {
43         val sliceString = sliceUri.getSliceId() ?: return null
44         val sliceData = sliceDataMap[sliceString] ?: return null
45         return if (sliceData.isActive()) sliceData else null
46     }
47 
buildLiveDataImplnull48     private fun buildLiveDataImpl(sliceUri: Uri): EntrySliceData? {
49         Log.d(TAG, "buildLiveData: $sliceUri")
50 
51         val entryId = sliceUri.getEntryId() ?: return null
52         val entry = entryRepository.getEntry(entryId) ?: return null
53         if (!entry.hasSliceSupport) return null
54         val arguments = sliceUri.getRuntimeArguments()
55         return entry.getSliceData(runtimeArguments = arguments, sliceUri = sliceUri)
56     }
57 }
58