summaryrefslogtreecommitdiff
path: root/src/com/android/customization/picker/theme/CustomThemeActivity.java
blob: 62a2f266c350186bf7e38021fa265f55550b985d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.customization.picker.theme;

import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.android.customization.model.CustomizationManager.Callback;
import com.android.customization.model.theme.DefaultThemeProvider;
import com.android.customization.model.theme.OverlayManagerCompat;
import com.android.customization.model.theme.ThemeBundle;
import com.android.customization.model.theme.ThemeBundleProvider;
import com.android.customization.model.theme.ThemeManager;
import com.android.customization.model.theme.custom.ColorOptionsProvider;
import com.android.customization.model.theme.custom.CustomTheme;
import com.android.customization.model.theme.custom.CustomThemeManager;
import com.android.customization.model.theme.custom.FontOptionsProvider;
import com.android.customization.model.theme.custom.IconOptionsProvider;
import com.android.customization.model.theme.custom.ShapeOptionsProvider;
import com.android.customization.model.theme.custom.ThemeComponentOption;
import com.android.customization.model.theme.custom.ThemeComponentOption.ColorOption;
import com.android.customization.model.theme.custom.ThemeComponentOption.FontOption;
import com.android.customization.model.theme.custom.ThemeComponentOption.IconOption;
import com.android.customization.model.theme.custom.ThemeComponentOption.ShapeOption;
import com.android.customization.model.theme.custom.ThemeComponentOptionProvider;
import com.android.customization.module.CustomizationInjector;
import com.android.customization.module.ThemesUserEventLogger;
import com.android.customization.picker.theme.CustomThemeStepFragment.CustomThemeComponentStepHost;
import com.android.wallpaper.R;
import com.android.wallpaper.module.InjectorProvider;
import com.android.wallpaper.picker.AppbarFragment.AppbarFragmentHost;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

public class CustomThemeActivity extends FragmentActivity implements
        AppbarFragmentHost, CustomThemeComponentStepHost {
    public static final String EXTRA_THEME_ID = "CustomThemeActivity.ThemeId";
    public static final String EXTRA_THEME_TITLE = "CustomThemeActivity.ThemeTitle";
    public static final String EXTRA_THEME_PACKAGES = "CustomThemeActivity.ThemePackages";
    public static final int REQUEST_CODE_CUSTOM_THEME = 1;
    public static final int RESULT_THEME_DELETED = 10;
    public static final int RESULT_THEME_APPLIED = 20;

    private static final String TAG = "CustomThemeActivity";
    private static final String KEY_STATE_CURRENT_STEP = "CustomThemeActivity.currentStep";

    private ThemesUserEventLogger mUserEventLogger;
    private List<ComponentStep<?>> mSteps;
    private int mCurrentStep;
    private CustomThemeManager mCustomThemeManager;
    private ThemeManager mThemeManager;
    private TextView mNextButton;
    private TextView mPreviousButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        CustomizationInjector injector = (CustomizationInjector) InjectorProvider.getInjector();
        mUserEventLogger = (ThemesUserEventLogger) injector.getUserEventLogger(this);
        ThemeBundleProvider themeProvider =
                new DefaultThemeProvider(this, injector.getCustomizationPreferences(this));
        Intent intent = getIntent();
        CustomTheme customTheme = null;
        if (intent != null && intent.hasExtra(EXTRA_THEME_PACKAGES)
                && intent.hasExtra(EXTRA_THEME_TITLE) && intent.hasExtra(EXTRA_THEME_ID)) {
            try {
                CustomTheme.Builder themeBuilder = themeProvider.parseCustomTheme(
                        intent.getStringExtra(EXTRA_THEME_PACKAGES));
                if (themeBuilder != null) {
                    themeBuilder.setId(intent.getStringExtra(EXTRA_THEME_ID));
                    themeBuilder.setTitle(intent.getStringExtra(EXTRA_THEME_TITLE));
                    customTheme = themeBuilder.build(this);
                }
            } catch (JSONException e) {
                Log.w(TAG, "Couldn't parse provided custom theme, will override it");
            }
        }

        mThemeManager = injector.getThemeManager(
                new DefaultThemeProvider(this, injector.getCustomizationPreferences(this)),
                this,
                new OverlayManagerCompat(this),
                mUserEventLogger);
        mThemeManager.fetchOptions(null, false);
        mCustomThemeManager = CustomThemeManager.create(customTheme, mThemeManager);
        if (savedInstanceState != null) {
            mCustomThemeManager.readCustomTheme(themeProvider, savedInstanceState);
        }

        int currentStep = 0;
        if (savedInstanceState != null) {
            currentStep = savedInstanceState.getInt(KEY_STATE_CURRENT_STEP);
        }
        initSteps(currentStep);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_theme);
        mNextButton = findViewById(R.id.next_button);
        mNextButton.setOnClickListener(view -> onNextOrApply());
        mPreviousButton = findViewById(R.id.previous_button);
        mPreviousButton.setOnClickListener(view -> onBackPressed());

        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment = fm.findFragmentById(R.id.fragment_container);
        if (fragment == null) {
            // Navigate to the first step
            navigateToStep(0);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(KEY_STATE_CURRENT_STEP, mCurrentStep);
        if (mCustomThemeManager != null) {
            mCustomThemeManager.saveCustomTheme(this, outState);
        }
    }

    private void navigateToStep(int i) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        ComponentStep step = mSteps.get(i);
        Fragment fragment = step.getFragment(mCustomThemeManager.getOriginalTheme().getTitle());

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        // Don't add step 0 to the back stack so that going back from it just finishes the Activity
        if (i > 0) {
            fragmentTransaction.addToBackStack("Step " + i);
        }
        fragmentTransaction.commit();
        fragmentManager.executePendingTransactions();
        updateNavigationButtonLabels();
    }

    private void initSteps(int currentStep) {
        mSteps = new ArrayList<>();
        OverlayManagerCompat manager = new OverlayManagerCompat(this);
        mSteps.add(new FontStep(new FontOptionsProvider(this, manager), 0));
        mSteps.add(new IconStep(new IconOptionsProvider(this, manager), 1));
        mSteps.add(new ColorStep(new ColorOptionsProvider(this, manager, mCustomThemeManager), 2));
        mSteps.add(new ShapeStep(new ShapeOptionsProvider(this, manager), 3));
        mSteps.add(new NameStep(4));
        mCurrentStep = currentStep;
    }

    private void onNextOrApply() {
        CustomThemeStepFragment stepFragment = getCurrentStepFragment();
        if (stepFragment instanceof CustomThemeComponentFragment) {
            CustomThemeComponentFragment fragment = (CustomThemeComponentFragment) stepFragment;
            mCustomThemeManager.apply(fragment.getSelectedOption(), new Callback() {
                @Override
                public void onSuccess() {
                    navigateToStep(mCurrentStep + 1);
                }

                @Override
                public void onError(@Nullable Throwable throwable) {
                    Log.w(TAG, "Error applying custom theme component", throwable);
                    Toast.makeText(CustomThemeActivity.this, R.string.apply_theme_error_msg,
                            Toast.LENGTH_LONG).show();
                }
            });
        } else if (stepFragment instanceof CustomThemeNameFragment) {
            CustomThemeNameFragment fragment = (CustomThemeNameFragment) stepFragment;
            CustomTheme originalTheme = mCustomThemeManager.getOriginalTheme();

            // We're on the last step, apply theme and leave
            CustomTheme themeToApply = mCustomThemeManager.buildPartialCustomTheme(this,
                    originalTheme.getId(), fragment.getThemeName());

            // If the current theme is equal to the original theme being edited, then
            // don't search for an equivalent, let the user apply the same one by keeping
            // it null.
            ThemeBundle equivalent = (originalTheme.isEquivalent(themeToApply))
                    ? null : mThemeManager.findThemeByPackages(themeToApply);

            if (equivalent != null) {
                Builder builder =
                        new Builder(CustomThemeActivity.this);
                builder.setTitle(getString(R.string.use_style_instead_title,
                        equivalent.getTitle()))
                        .setMessage(getString(R.string.use_style_instead_body,
                                equivalent.getTitle()))
                        .setPositiveButton(getString(R.string.use_style_button,
                                equivalent.getTitle()),
                                (dialogInterface, i) -> applyTheme(equivalent))
                        .setNegativeButton(R.string.no_thanks, null)
                        .create()
                        .show();
            } else {
                applyTheme(themeToApply);
            }
        } else {
            throw new IllegalStateException("Unknown CustomThemeStepFragment");
        }
    }

    private void applyTheme(ThemeBundle themeToApply) {
        mThemeManager.apply(themeToApply, new Callback() {
            @Override
            public void onSuccess() {
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                Toast.makeText(getApplicationContext(), R.string.applied_theme_msg,
                        Toast.LENGTH_LONG).show();
                setResult(RESULT_THEME_APPLIED);
                finish();
            }

            @Override
            public void onError(@Nullable Throwable throwable) {
                Log.w(TAG, "Error applying custom theme", throwable);
                Toast.makeText(CustomThemeActivity.this,
                        R.string.apply_theme_error_msg,
                        Toast.LENGTH_LONG).show();
            }
        });
    }

    private CustomThemeStepFragment getCurrentStepFragment() {
        return (CustomThemeStepFragment)
                getSupportFragmentManager().findFragmentById(R.id.fragment_container);
    }

    @Override
    public void setCurrentStep(int i) {
        mCurrentStep = i;
        updateNavigationButtonLabels();
    }

    private void updateNavigationButtonLabels() {
        mPreviousButton.setVisibility(mCurrentStep == 0 ? View.INVISIBLE : View.VISIBLE);
        mNextButton.setText((mCurrentStep < mSteps.size() -1) ? R.string.custom_theme_next
                : R.string.apply_btn);
    }

    @Override
    public void delete() {
        mThemeManager.removeCustomTheme(mCustomThemeManager.getOriginalTheme());
        setResult(RESULT_THEME_DELETED);
        finish();
    }

    @Override
    public void cancel() {
        finish();
    }

    @Override
    public ThemeComponentOptionProvider<? extends ThemeComponentOption> getComponentOptionProvider(
            int position) {
        return mSteps.get(position).provider;
    }

    @Override
    public CustomThemeManager getCustomThemeManager() {
        return mCustomThemeManager;
    }

    @Override
    public void onUpArrowPressed() {
        // Skip it because CustomThemeStepFragment will implement cancel button
        // (instead of up arrow) on action bar.
    }

    @Override
    public boolean isUpArrowSupported() {
        // Skip it because CustomThemeStepFragment will implement cancel button
        // (instead of up arrow) on action bar.
        return false;
    }

    /**
     * Represents a step in selecting a custom theme, picking a particular component (eg font,
     * color, shape, etc).
     * Each step has a Fragment instance associated that instances of this class will provide.
     */
    private static abstract class ComponentStep<T extends ThemeComponentOption> {
        @StringRes final int titleResId;
        @StringRes final int accessibilityResId;
        final ThemeComponentOptionProvider<T> provider;
        final int position;
        private CustomThemeStepFragment mFragment;

        protected ComponentStep(@StringRes int titleResId, @StringRes int accessibilityResId,
                ThemeComponentOptionProvider<T> provider, int position) {
            this.titleResId = titleResId;
            this.accessibilityResId = accessibilityResId;
            this.provider = provider;
            this.position = position;
        }

        CustomThemeStepFragment getFragment(String title) {
            if (mFragment == null) {
                mFragment = createFragment(title);
            }
            return mFragment;
        }

        /**
         * @return a newly created fragment that will handle this step's UI.
         */
        abstract CustomThemeStepFragment createFragment(String title);
    }

    private class FontStep extends ComponentStep<FontOption> {

        protected FontStep(ThemeComponentOptionProvider<FontOption> provider,
                int position) {
            super(R.string.font_component_title, R.string.accessibility_custom_font_title, provider,
                    position);
        }

        @Override
        CustomThemeComponentFragment createFragment(String title) {
            return CustomThemeComponentFragment.newInstance(
                    title,
                    position,
                    titleResId,
                    accessibilityResId);
        }
    }

    private class IconStep extends ComponentStep<IconOption> {

        protected IconStep(ThemeComponentOptionProvider<IconOption> provider,
                int position) {
            super(R.string.icon_component_title, R.string.accessibility_custom_icon_title, provider,
                    position);
        }

        @Override
        CustomThemeComponentFragment createFragment(String title) {
            return CustomThemeComponentFragment.newInstance(
                    title,
                    position,
                    titleResId,
                    accessibilityResId);
        }
    }

    private class ColorStep extends ComponentStep<ColorOption> {

        protected ColorStep(ThemeComponentOptionProvider<ColorOption> provider,
                int position) {
            super(R.string.color_component_title, R.string.accessibility_custom_color_title,
                    provider, position);
        }

        @Override
        CustomThemeComponentFragment createFragment(String title) {
            return CustomThemeComponentFragment.newInstance(
                    title,
                    position,
                    titleResId,
                    accessibilityResId);
        }
    }

    private class ShapeStep extends ComponentStep<ShapeOption> {

        protected ShapeStep(ThemeComponentOptionProvider<ShapeOption> provider,
                int position) {
            super(R.string.shape_component_title, R.string.accessibility_custom_shape_title,
                    provider, position);
        }

        @Override
        CustomThemeComponentFragment createFragment(String title) {
            return CustomThemeComponentFragment.newInstance(
                    title,
                    position,
                    titleResId,
                    accessibilityResId);
        }
    }

    private class NameStep extends ComponentStep {

        protected NameStep(int position) {
            super(R.string.name_component_title, R.string.accessibility_custom_name_title, null,
                    position);
        }

        @Override
        CustomThemeNameFragment createFragment(String title) {
            return CustomThemeNameFragment.newInstance(
                    title,
                    position,
                    titleResId,
                    accessibilityResId);
        }
    }
}