1/*
2 * Copyright (C) 2017 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
17package com.android.systemui;
18
19import android.annotation.Nullable;
20import android.content.Context;
21import android.content.res.TypedArray;
22import android.util.AttributeSet;
23import android.widget.ImageView;
24
25import com.android.systemui.statusbar.policy.BatteryController;
26import com.android.systemui.statusbar.policy.ConfigurationController;
27
28/**
29 * A view that only shows its drawable while the phone is charging.
30 *
31 * Also reloads its drawable upon density changes.
32 */
33public class ChargingView extends ImageView implements
34        BatteryController.BatteryStateChangeCallback,
35        ConfigurationController.ConfigurationListener {
36
37    private BatteryController mBatteryController;
38    private int mImageResource;
39    private boolean mCharging;
40    private boolean mDark;
41
42    public ChargingView(Context context, @Nullable AttributeSet attrs) {
43        super(context, attrs);
44
45        TypedArray a = context.obtainStyledAttributes(attrs, new int[]{android.R.attr.src});
46        int srcResId = a.getResourceId(0, 0);
47
48        if (srcResId != 0) {
49            mImageResource = srcResId;
50        }
51
52        a.recycle();
53
54        updateVisibility();
55    }
56
57    @Override
58    public void onAttachedToWindow() {
59        super.onAttachedToWindow();
60        mBatteryController = Dependency.get(BatteryController.class);
61        mBatteryController.addCallback(this);
62        Dependency.get(ConfigurationController.class).addCallback(this);
63    }
64
65    @Override
66    public void onDetachedFromWindow() {
67        super.onDetachedFromWindow();
68        mBatteryController.removeCallback(this);
69        Dependency.get(ConfigurationController.class).removeCallback(this);
70    }
71
72    @Override
73    public void onBatteryLevelChanged(int level, boolean pluggedIn, boolean charging) {
74        mCharging = charging;
75        updateVisibility();
76    }
77
78    @Override
79    public void onDensityOrFontScaleChanged() {
80        setImageResource(mImageResource);
81    }
82
83    public void setDark(boolean dark) {
84        mDark = dark;
85        updateVisibility();
86    }
87
88    private void updateVisibility() {
89        setVisibility(mCharging && mDark ? VISIBLE : INVISIBLE);
90    }
91}
92