NavBarTuner.java revision ea05f87b253ce20a08158768951169b1cda0a623
1/*
2 * Copyright (C) 2017 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 static com.android.systemui.statusbar.phone.NavigationBarInflaterView.KEY;
18import static com.android.systemui.statusbar.phone.NavigationBarInflaterView.KEY_CODE_END;
19import static com.android.systemui.statusbar.phone.NavigationBarInflaterView.KEY_CODE_START;
20import static com.android.systemui.statusbar.phone.NavigationBarInflaterView.KEY_IMAGE_DELIM;
21import static com.android.systemui.statusbar.phone.NavigationBarInflaterView.MENU_IME;
22import static com.android.systemui.statusbar.phone.NavigationBarInflaterView.NAVSPACE;
23import static com.android.systemui.statusbar.phone.NavigationBarInflaterView.NAV_BAR_LEFT;
24import static com.android.systemui.statusbar.phone.NavigationBarInflaterView.NAV_BAR_RIGHT;
25import static com.android.systemui.statusbar.phone.NavigationBarInflaterView.NAV_BAR_VIEWS;
26import static com.android.systemui.statusbar.phone.NavigationBarInflaterView.extractButton;
27import static com.android.systemui.statusbar.phone.NavigationBarInflaterView.extractImage;
28import static com.android.systemui.statusbar.phone.NavigationBarInflaterView.extractKeycode;
29
30import android.annotation.Nullable;
31import android.app.AlertDialog;
32import android.content.DialogInterface;
33import android.content.DialogInterface.OnClickListener;
34import android.content.res.Resources;
35import android.graphics.Color;
36import android.graphics.drawable.Drawable;
37import android.graphics.drawable.Icon;
38import android.os.Bundle;
39import android.os.Handler;
40import android.support.v14.preference.PreferenceFragment;
41import android.support.v7.preference.DropDownPreference;
42import android.support.v7.preference.ListPreference;
43import android.support.v7.preference.Preference;
44import android.support.v7.preference.Preference.OnPreferenceChangeListener;
45import android.support.v7.preference.Preference.OnPreferenceClickListener;
46import android.support.v7.preference.PreferenceCategory;
47import android.text.SpannableStringBuilder;
48import android.text.style.ImageSpan;
49import android.util.Log;
50import android.util.TypedValue;
51import android.view.KeyEvent;
52import android.widget.EditText;
53
54import com.android.systemui.R;
55import com.android.systemui.statusbar.phone.NavigationBarInflaterView;
56import com.android.systemui.tuner.TunerService.Tunable;
57
58import java.util.ArrayList;
59
60public class NavBarTuner extends PreferenceFragment {
61
62    private static final String LAYOUT = "layout";
63    private static final String LEFT = "left";
64    private static final String RIGHT = "right";
65
66    private static final String TYPE = "type";
67    private static final String KEYCODE = "keycode";
68    private static final String ICON = "icon";
69
70    private static final int[] ICONS = new int[]{
71            R.drawable.ic_qs_circle,
72            R.drawable.ic_add,
73            R.drawable.ic_remove,
74            R.drawable.ic_left,
75            R.drawable.ic_right,
76            R.drawable.ic_menu,
77    };
78
79    private final ArrayList<Tunable> mTunables = new ArrayList<>();
80    private Handler mHandler;
81
82    @Override
83    public void onCreate(@Nullable Bundle savedInstanceState) {
84        mHandler = new Handler();
85        super.onCreate(savedInstanceState);
86    }
87
88    @Override
89    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
90        super.onActivityCreated(savedInstanceState);
91        getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
92    }
93
94    @Override
95    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
96        addPreferencesFromResource(R.xml.nav_bar_tuner);
97        bindLayout((ListPreference) findPreference(LAYOUT));
98        bindButton((PreferenceCategory) findPreference(LEFT),
99                NAV_BAR_LEFT, NAVSPACE);
100        bindButton((PreferenceCategory) findPreference(RIGHT),
101                NAV_BAR_RIGHT, MENU_IME);
102    }
103
104    @Override
105    public void onDestroy() {
106        super.onDestroy();
107        mTunables.forEach(t -> TunerService.get(getContext()).removeTunable(t));
108    }
109
110    private void addTunable(Tunable tunable, String... keys) {
111        mTunables.add(tunable);
112        TunerService.get(getContext()).addTunable(tunable, keys);
113    }
114
115    private void bindLayout(ListPreference preference) {
116        addTunable((key, newValue) -> mHandler.post(() -> {
117            String val = newValue;
118            if (val == null) {
119                val = "default";
120            }
121            preference.setValue(val);
122        }), NAV_BAR_VIEWS);
123        preference.setOnPreferenceChangeListener((preference1, newValue) -> {
124            String val = (String) newValue;
125            if ("default".equals(val)) val = null;
126            TunerService.get(getContext()).setValue(NAV_BAR_VIEWS, val);
127            return true;
128        });
129    }
130
131    private void bindButton(PreferenceCategory parent, String setting, String def) {
132        String k = parent.getKey();
133        DropDownPreference type = (DropDownPreference) findPreference(TYPE + "_" + k);
134        Preference keycode = findPreference(KEYCODE + "_" + k);
135        ListPreference icon = (ListPreference) findPreference(ICON + "_" + k);
136        setupIcons(icon);
137        addTunable((key, newValue) -> mHandler.post(() -> {
138            String val = newValue;
139            if (val == null) {
140                val = def;
141            }
142            String button = extractButton(val);
143            if (button.startsWith(KEY)) {
144                type.setValue(KEY);
145                String uri = extractImage(button);
146                int code = extractKeycode(button);
147                icon.setValue(uri);
148                updateSummary(icon);
149                keycode.setSummary(code + "");
150                keycode.setVisible(true);
151                icon.setVisible(true);
152            } else {
153                type.setValue(button);
154                keycode.setVisible(false);
155                icon.setVisible(false);
156            }
157        }), setting);
158        OnPreferenceChangeListener listener = (preference, newValue) -> {
159            mHandler.post(() -> {
160                setValue(setting, type, keycode, icon);
161                updateSummary(icon);
162            });
163            return true;
164        };
165        type.setOnPreferenceChangeListener(listener);
166        icon.setOnPreferenceChangeListener(listener);
167        keycode.setOnPreferenceClickListener(preference -> {
168            EditText editText = new EditText(getContext());
169            new AlertDialog.Builder(getContext())
170                    .setTitle(preference.getTitle())
171                    .setView(editText)
172                    .setNegativeButton(android.R.string.cancel, null)
173                    .setPositiveButton(android.R.string.ok, (dialog, which) -> {
174                        int code = KeyEvent.KEYCODE_ENTER;
175                        try {
176                            code = Integer.parseInt(editText.getText().toString());
177                        } catch (Exception e) {
178                        }
179                        keycode.setSummary(code + "");
180                        setValue(setting, type, keycode, icon);
181                    }).show();
182            return true;
183        });
184    }
185
186    private void updateSummary(ListPreference icon) {
187        try {
188            int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14,
189                    getContext().getResources().getDisplayMetrics());
190            String pkg = icon.getValue().split("/")[0];
191            int id = Integer.parseInt(icon.getValue().split("/")[1]);
192            SpannableStringBuilder builder = new SpannableStringBuilder();
193            Drawable d = Icon.createWithResource(pkg, id)
194                    .loadDrawable(getContext());
195            d.setTint(Color.BLACK);
196            d.setBounds(0, 0, size, size);
197            ImageSpan span = new ImageSpan(d);
198            builder.append("  ", span, 0);
199            icon.setSummary(builder);
200        } catch (Exception e) {
201            Log.d("NavButton", "Problem with summary", e);
202            icon.setSummary(null);
203        }
204    }
205
206    private void setValue(String setting, DropDownPreference type, Preference keycode,
207            ListPreference icon) {
208        String button = type.getValue();
209        if (KEY.equals(button)) {
210            String uri = icon.getValue();
211            int code = KeyEvent.KEYCODE_ENTER;
212            try {
213                code = Integer.parseInt(keycode.getSummary().toString());
214            } catch (Exception e) {
215            }
216            button = button + KEY_CODE_START + code + KEY_IMAGE_DELIM + uri + KEY_CODE_END;
217        }
218        TunerService.get(getContext()).setValue(setting, button);
219    }
220
221    private void setupIcons(ListPreference icon) {
222        CharSequence[] labels = new CharSequence[ICONS.length];
223        CharSequence[] values = new CharSequence[ICONS.length];
224        int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14,
225                getContext().getResources().getDisplayMetrics());
226        for (int i = 0; i < ICONS.length; i++) {
227            SpannableStringBuilder builder = new SpannableStringBuilder();
228            Drawable d = Icon.createWithResource(getContext().getPackageName(), ICONS[i])
229                    .loadDrawable(getContext());
230            d.setTint(Color.BLACK);
231            d.setBounds(0, 0, size, size);
232            ImageSpan span = new ImageSpan(d);
233            builder.append("  ", span, 0);
234            labels[i] = builder;
235            values[i] = getContext().getPackageName() + "/" + ICONS[i];
236        }
237        icon.setEntries(labels);
238        icon.setEntryValues(values);
239    }
240}
241