1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5 * except in compliance with the License. You may obtain a copy of the License at
6 *
7 *      http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
11 * KIND, either express or implied. See the License for the specific language governing
12 * permissions and limitations under the License.
13 */
14
15package com.android.systemui.tuner;
16
17import android.content.Context;
18import android.util.AttributeSet;
19import android.view.MotionEvent;
20
21import com.android.systemui.Dependency;
22import com.android.systemui.statusbar.phone.NavigationBarInflaterView;
23
24public class PreviewNavInflater extends NavigationBarInflaterView {
25
26    public PreviewNavInflater(Context context, AttributeSet attrs) {
27        super(context, attrs);
28    }
29
30    @Override
31    protected void onAttachedToWindow() {
32        super.onAttachedToWindow();
33        // Immediately remove tuner listening, since this is a preview, all values will be injected
34        // manually.
35        Dependency.get(TunerService.class).removeTunable(this);
36    }
37
38    @Override
39    public boolean onInterceptTouchEvent(MotionEvent ev) {
40        // Only a preview, not interactable.
41        return true;
42    }
43
44    @Override
45    public void onTuningChanged(String key, String newValue) {
46        if (NAV_BAR_VIEWS.equals(key)) {
47            // Since this is a preview we might get a bunch of random stuff, validate before sending
48            // for inflation.
49            if (isValidLayout(newValue)) {
50                super.onTuningChanged(key, newValue);
51            }
52        } else {
53            super.onTuningChanged(key, newValue);
54        }
55    }
56
57    private boolean isValidLayout(String newValue) {
58        if (newValue == null) {
59            return true;
60        }
61        int separatorCount = 0;
62        int lastGravitySeparator = 0;
63        for (int i = 0; i < newValue.length(); i++) {
64            if (newValue.charAt(i) == GRAVITY_SEPARATOR.charAt(0)) {
65                if (i == 0 || (i - lastGravitySeparator) == 1) {
66                    return false;
67                }
68                lastGravitySeparator = i;
69                separatorCount++;
70            }
71        }
72        return separatorCount == 2 && (newValue.length() - lastGravitySeparator) != 1;
73    }
74}
75