1 /*
2  * Copyright (C) 2023 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.systemui.car;
18 
19 import android.content.Context;
20 import android.content.ContextWrapper;
21 import android.util.ArrayMap;
22 import android.util.Dumpable;
23 import android.util.DumpableContainer;
24 import android.util.Log;
25 
26 import com.android.systemui.dump.DumpManager;
27 
28 import javax.annotation.concurrent.GuardedBy;
29 
30 /**
31  * Context Wrapper that is Dumpable.
32  */
33 public class CarDumpableContext extends ContextWrapper implements DumpableContainer {
34     private static final String TAG = CarDumpableContext.class.getName();
35     private static final boolean DEBUG = false;
36     private final Object mLock = new Object();
37     @GuardedBy("mLock")
38     private final ArrayMap<String, Dumpable> mDumpables = new ArrayMap<>();
39     private final DumpManager mDumpManager;
40 
CarDumpableContext(Context base, DumpManager dumpManager)41     public CarDumpableContext(Context base, DumpManager dumpManager) {
42         super(base);
43         mDumpManager = dumpManager;
44     }
45 
46     @Override
addDumpable(Dumpable dumpable)47     public boolean addDumpable(Dumpable dumpable) {
48         String name = dumpable.getDumpableName();
49         synchronized (mLock) {
50             if (mDumpables.containsKey(name)) {
51                 if (DEBUG) {
52                     Log.d(TAG, "addDumpable(): ignoring " + dumpable
53                             + " as there is already a dumpable with that name (" + name + "): "
54                             + mDumpables.get(name));
55                 }
56                 return false;
57             }
58             if (DEBUG) Log.d(TAG, "addDumpable(): adding '" + name + "' = " + dumpable);
59             mDumpables.put(name, dumpable);
60             mDumpManager.registerNormalDumpable(dumpable.getDumpableName(), dumpable::dump);
61         }
62         return true;
63     }
64 
65     @Override
removeDumpable(Dumpable dumpable)66     public boolean removeDumpable(Dumpable dumpable) {
67         String name = dumpable.getDumpableName();
68         synchronized (mLock) {
69             mDumpManager.unregisterDumpable(name);
70             mDumpables.remove(name);
71         }
72         return true;
73     }
74 }
75