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 
17 package androidx.window.common;
18 
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.content.Context;
22 import android.text.TextUtils;
23 import android.util.Log;
24 
25 import androidx.window.util.BaseDataProducer;
26 
27 import com.android.internal.R;
28 
29 import java.util.ArrayList;
30 import java.util.List;
31 import java.util.Optional;
32 
33 /**
34  * Implementation of {@link androidx.window.util.DataProducer} that produces
35  * {@link CommonDisplayFeature} parsed from a string stored in the resources config at
36  * {@link R.string#config_display_features}.
37  */
38 public final class ResourceConfigDisplayFeatureProducer extends
39         BaseDataProducer<List<DisplayFeature>> {
40     private static final boolean DEBUG = false;
41     private static final String TAG = "ResourceConfigDisplayFeatureProducer";
42 
43     private final Context mContext;
44 
ResourceConfigDisplayFeatureProducer(@onNull Context context)45     public ResourceConfigDisplayFeatureProducer(@NonNull Context context) {
46         mContext = context;
47     }
48 
49     @Override
50     @Nullable
getData()51     public Optional<List<DisplayFeature>> getData() {
52         String displayFeaturesString = mContext.getResources().getString(
53                 R.string.config_display_features);
54         if (TextUtils.isEmpty(displayFeaturesString)) {
55             return Optional.empty();
56         }
57 
58         List<DisplayFeature> features = new ArrayList<>();
59         String[] featureStrings =  displayFeaturesString.split(";");
60         for (String featureString : featureStrings) {
61             CommonDisplayFeature feature;
62             try {
63                 feature = CommonDisplayFeature.parseFromString(featureString);
64             } catch (IllegalArgumentException e) {
65                 if (DEBUG) {
66                     Log.w(TAG, "Failed to parse display feature: " + featureString, e);
67                 }
68                 continue;
69             }
70             features.add(feature);
71         }
72         return Optional.of(features);
73     }
74 }
75