blob: 40627b5099e69c8cf905573dc1b867c337b7d276 [file] [log] [blame]
Jon Miranda16ea1b12017-12-12 14:52:48 -08001/*
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 */
16package com.android.wallpaper.picker;
17
Jon Miranda16ea1b12017-12-12 14:52:48 -080018import android.app.Activity;
19import android.app.ProgressDialog;
Jon Miranda16ea1b12017-12-12 14:52:48 -080020import android.content.Context;
21import android.content.Intent;
Jon Miranda16ea1b12017-12-12 14:52:48 -080022import android.graphics.Color;
Santiago Etchebehere35891ea2019-07-26 15:21:42 -070023import android.graphics.Insets;
Jon Miranda16ea1b12017-12-12 14:52:48 -080024import android.graphics.PorterDuff.Mode;
25import android.graphics.drawable.Drawable;
26import android.net.Uri;
27import android.os.AsyncTask;
28import android.os.Build.VERSION;
29import android.os.Build.VERSION_CODES;
30import android.os.Bundle;
Hyunyoung Song8077c862019-06-18 01:14:24 -040031import android.provider.Settings;
Jon Miranda16ea1b12017-12-12 14:52:48 -080032import android.util.Log;
33import android.view.View;
34import android.view.View.OnClickListener;
Santiago Etchebehere35891ea2019-07-26 15:21:42 -070035import android.view.WindowInsets;
Jon Miranda16ea1b12017-12-12 14:52:48 -080036import android.widget.Button;
37import android.widget.FrameLayout;
38import android.widget.ImageView;
39import android.widget.LinearLayout;
40import android.widget.TextView;
41
Santiago Etchebehere635e96f2018-12-04 18:31:34 -080042import androidx.annotation.NonNull;
43import androidx.annotation.Nullable;
44import androidx.appcompat.app.AlertDialog;
45import androidx.appcompat.widget.Toolbar;
46import androidx.fragment.app.Fragment;
47import androidx.fragment.app.FragmentManager;
48
Jon Miranda16ea1b12017-12-12 14:52:48 -080049import com.android.wallpaper.R;
50import com.android.wallpaper.asset.Asset;
Santiago Etchebehere35891ea2019-07-26 15:21:42 -070051import com.android.wallpaper.compat.BuildCompat;
Jon Miranda16ea1b12017-12-12 14:52:48 -080052import com.android.wallpaper.compat.ButtonDrawableSetterCompat;
Jon Miranda16ea1b12017-12-12 14:52:48 -080053import com.android.wallpaper.config.Flags;
54import com.android.wallpaper.model.Category;
Jon Miranda16ea1b12017-12-12 14:52:48 -080055import com.android.wallpaper.model.ImageWallpaperInfo;
Jon Miranda16ea1b12017-12-12 14:52:48 -080056import com.android.wallpaper.model.WallpaperInfo;
57import com.android.wallpaper.module.CurrentWallpaperInfoFactory;
58import com.android.wallpaper.module.CurrentWallpaperInfoFactory.WallpaperInfoCallback;
59import com.android.wallpaper.module.DailyLoggingAlarmScheduler;
60import com.android.wallpaper.module.ExploreIntentChecker;
61import com.android.wallpaper.module.FormFactorChecker;
Jon Miranda16ea1b12017-12-12 14:52:48 -080062import com.android.wallpaper.module.Injector;
63import com.android.wallpaper.module.InjectorProvider;
64import com.android.wallpaper.module.NetworkStatusNotifier;
65import com.android.wallpaper.module.NetworkStatusNotifier.NetworkStatus;
66import com.android.wallpaper.module.UserEventLogger;
67import com.android.wallpaper.module.UserEventLogger.WallpaperSetFailureReason;
68import com.android.wallpaper.module.WallpaperPersister;
69import com.android.wallpaper.module.WallpaperPersister.Destination;
70import com.android.wallpaper.module.WallpaperPersister.SetWallpaperCallback;
71import com.android.wallpaper.module.WallpaperPersister.WallpaperPosition;
72import com.android.wallpaper.module.WallpaperPreferences;
73import com.android.wallpaper.module.WallpaperPreferences.PresentationMode;
74import com.android.wallpaper.module.WallpaperRotationRefresher;
75import com.android.wallpaper.module.WallpaperRotationRefresher.Listener;
Santiago Etchebehere635e96f2018-12-04 18:31:34 -080076import com.android.wallpaper.picker.CategoryFragment.CategoryFragmentHost;
Jon Miranda16ea1b12017-12-12 14:52:48 -080077import com.android.wallpaper.picker.WallpaperDisabledFragment.WallpaperSupportLevel;
Jon Miranda16ea1b12017-12-12 14:52:48 -080078import com.android.wallpaper.picker.individual.IndividualPickerFragment;
79import com.android.wallpaper.util.ScreenSizeCalculator;
80import com.android.wallpaper.util.ThrowableAnalyzer;
chihhangchuang3efb6832020-04-17 02:06:25 +080081import com.android.wallpaper.widget.BottomActionBar;
82import com.android.wallpaper.widget.BottomActionBar.BottomActionBarHost;
Jon Miranda16ea1b12017-12-12 14:52:48 -080083
Sunny Goyal8600a3f2018-08-15 12:48:01 -070084import com.google.android.material.bottomsheet.BottomSheetBehavior;
85import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback;
86import com.google.android.material.tabs.TabLayout;
87import com.google.android.material.tabs.TabLayout.OnTabSelectedListener;
88import com.google.android.material.tabs.TabLayout.Tab;
89
Jon Miranda16ea1b12017-12-12 14:52:48 -080090import java.util.List;
91
92/**
93 * Activity allowing users to select a category of wallpapers to choose from.
94 */
95public class TopLevelPickerActivity extends BaseActivity implements WallpapersUiContainer,
96 CurrentWallpaperBottomSheetPresenter, SetWallpaperErrorDialogFragment.Listener,
chihhangchuang3efb6832020-04-17 02:06:25 +080097 MyPhotosStarter, CategoryFragmentHost, BottomActionBarHost {
Jon Miranda16ea1b12017-12-12 14:52:48 -080098
99 private static final String TAG_SET_WALLPAPER_ERROR_DIALOG_FRAGMENT =
100 "toplevel_set_wallpaper_error_dialog";
101
102 private static final String TAG = "TopLevelPicker";
103 private static final String KEY_SELECTED_CATEGORY_TAB = "selected_category_tab";
104
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800105 private WallpaperPickerDelegate mDelegate;
Jon Miranda16ea1b12017-12-12 14:52:48 -0800106 private int mLastSelectedCategoryTabIndex;
Jon Miranda16ea1b12017-12-12 14:52:48 -0800107 private UserEventLogger mUserEventLogger;
108 private NetworkStatusNotifier mNetworkStatusNotifier;
109 private NetworkStatusNotifier.Listener mNetworkStatusListener;
110 private WallpaperPersister mWallpaperPersister;
Kunhung Li166842e2020-05-13 19:19:06 +0800111 private WallpaperPreferences mWallpaperPreferences;
Jon Miranda16ea1b12017-12-12 14:52:48 -0800112 private boolean mWasCustomPhotoWallpaperSet;
113 @WallpaperPosition
114 private int mCustomPhotoWallpaperPosition;
115
116 /**
117 * Progress dialogs for "refresh daily wallpaper" and "set wallpaper" operations.
118 */
119 private ProgressDialog mRefreshWallpaperProgressDialog;
120 private ProgressDialog mSetWallpaperProgressDialog;
121
122 /**
123 * Designates a test mode of operation -- in which certain UI features are disabled to allow for
124 * UI tests to run correctly.
125 */
126 private boolean mTestingMode;
127
128 /**
129 * UI for the "currently set wallpaper" BottomSheet.
130 */
131 private LinearLayout mBottomSheet;
132 private ImageView mCurrentWallpaperImage;
133 private TextView mCurrentWallpaperPresentationMode;
134 private TextView mCurrentWallpaperTitle;
135 private TextView mCurrentWallpaperSubtitle;
136 private Button mCurrentWallpaperExploreButton;
137 private Button mCurrentWallpaperSkipWallpaperButton;
138 private FrameLayout mFragmentContainer;
139 private FrameLayout mLoadingIndicatorContainer;
140 private LinearLayout mWallpaperPositionOptions;
141
Jon Miranda16ea1b12017-12-12 14:52:48 -0800142 /**
143 * Staged error dialog fragments that were unable to be shown when the activity didn't allow
144 * committing fragment transactions.
145 */
146 private SetWallpaperErrorDialogFragment mStagedSetWallpaperErrorDialogFragment;
147
148 /**
149 * A wallpaper pending set to the device--we retain a reference to this in order to facilitate
150 * retry or re-crop operations.
151 */
152 private WallpaperInfo mPendingSetWallpaperInfo;
153
154 private static int getTextColorIdForWallpaperPositionButton(boolean isSelected) {
155 return isSelected ? R.color.accent_color : R.color.material_grey500;
156 }
157
158 @Override
159 protected void onCreate(Bundle savedInstanceState) {
160 super.onCreate(savedInstanceState);
161
Jon Miranda16ea1b12017-12-12 14:52:48 -0800162 mLastSelectedCategoryTabIndex = -1;
163
164 Injector injector = InjectorProvider.getInjector();
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800165 mDelegate = new WallpaperPickerDelegate(this, this, injector);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800166 mUserEventLogger = injector.getUserEventLogger(this);
167 mNetworkStatusNotifier = injector.getNetworkStatusNotifier(this);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800168 mWallpaperPersister = injector.getWallpaperPersister(this);
Kunhung Li83f72a82020-06-02 11:05:10 +0800169 mWallpaperPreferences = injector.getPreferences(this);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800170 mWasCustomPhotoWallpaperSet = false;
171
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800172 @WallpaperSupportLevel int wallpaperSupportLevel = mDelegate.getWallpaperSupportLevel();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800173 if (wallpaperSupportLevel != WallpaperDisabledFragment.SUPPORTED_CAN_SET) {
Chuck Liao8ec38e02020-02-26 20:59:32 +0800174 setContentView(R.layout.activity_top_level_picker);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800175
176 FragmentManager fm = getSupportFragmentManager();
177 WallpaperDisabledFragment wallpaperDisabledFragment =
178 WallpaperDisabledFragment.newInstance(wallpaperSupportLevel);
179 fm.beginTransaction()
180 .add(R.id.fragment_container, wallpaperDisabledFragment)
181 .commit();
182 return;
183 }
184
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800185 if (mDelegate.getFormFactor() == FormFactorChecker.FORM_FACTOR_MOBILE) {
Ching-Sung Li5f689972019-05-20 17:16:57 +0800186 initializeMobile(true /* shouldForceRefresh */);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800187 } else { // DESKTOP
188 initializeDesktop(savedInstanceState);
189 }
190 }
191
192 @Override
193 protected void onResume() {
194 super.onResume();
Hyunyoung Song8077c862019-06-18 01:14:24 -0400195 boolean provisioned = Settings.Global.getInt(getContentResolver(),
196 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
197
198 mUserEventLogger.logResumed(provisioned, true);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800199 // Show the staged 'load wallpaper' or 'set wallpaper' error dialog fragments if there is one
200 // that was unable to be shown earlier when this fragment's hosting activity didn't allow
201 // committing fragment transactions.
202 if (mStagedSetWallpaperErrorDialogFragment != null) {
203 mStagedSetWallpaperErrorDialogFragment.show(
204 getSupportFragmentManager(), TAG_SET_WALLPAPER_ERROR_DIALOG_FRAGMENT);
205 mStagedSetWallpaperErrorDialogFragment = null;
206 }
207 }
208
209 @Override
Santiago Etchebeherebd536c62019-04-09 15:25:51 -0300210 protected void onStop() {
211 mUserEventLogger.logStopped();
212 super.onStop();
213 }
214
215 @Override
Jon Miranda16ea1b12017-12-12 14:52:48 -0800216 protected void onDestroy() {
217 super.onDestroy();
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800218 mDelegate.cleanUp();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800219 if (mNetworkStatusListener != null) {
220 mNetworkStatusNotifier.unregisterListener(mNetworkStatusListener);
221 }
222
223 if (mRefreshWallpaperProgressDialog != null) {
224 mRefreshWallpaperProgressDialog.dismiss();
225 }
226 if (mSetWallpaperProgressDialog != null) {
227 mSetWallpaperProgressDialog.dismiss();
228 }
Jon Miranda16ea1b12017-12-12 14:52:48 -0800229 }
230
231 @Override
Chuck Liaob1f1a3a2020-02-17 19:46:14 +0800232 public void onBackPressed() {
Chuck Liaof24418e2020-05-10 02:29:44 +0800233 Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
234 if (fragment instanceof BottomActionBarFragment
235 && ((BottomActionBarFragment) fragment).onBackPressed()) {
236 return;
237 }
238
Chuck Liaob1f1a3a2020-02-17 19:46:14 +0800239 CategoryFragment categoryFragment = getCategoryFragment();
240 if (categoryFragment != null && categoryFragment.popChildFragment()) {
241 return;
242 }
243 super.onBackPressed();
244 }
245
246 @Override
Jon Miranda16ea1b12017-12-12 14:52:48 -0800247 public void requestCustomPhotoPicker(PermissionChangedListener listener) {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800248 mDelegate.requestCustomPhotoPicker(listener);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800249 }
250
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800251 @Override
252 public void requestExternalStoragePermission(PermissionChangedListener listener) {
253 mDelegate.requestExternalStoragePermission(listener);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800254 }
255
256 /**
257 * Returns whether READ_EXTERNAL_STORAGE has been granted for the application.
258 */
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800259 public boolean isReadExternalStoragePermissionGranted() {
260 return mDelegate.isReadExternalStoragePermissionGranted();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800261 }
262
Ching-Sung Li5f689972019-05-20 17:16:57 +0800263 private void initializeMobile(boolean shouldForceRefresh) {
Chuck Liao8ec38e02020-02-26 20:59:32 +0800264 setContentView(R.layout.activity_top_level_picker);
Santiago Etchebehere35891ea2019-07-26 15:21:42 -0700265 getWindow().getDecorView().setSystemUiVisibility(
266 getWindow().getDecorView().getSystemUiVisibility()
267 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
268 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
Chuck Liao829d4d22020-05-07 17:00:10 +0800269 View fragmentContainer = findViewById(R.id.fragment_container);
270 fragmentContainer.setOnApplyWindowInsetsListener((view, windowInsets) -> {
Santiago Etchebehere35891ea2019-07-26 15:21:42 -0700271 view.setPadding(view.getPaddingLeft(), windowInsets.getSystemWindowInsetTop(),
Chuck Liaoe9d79812020-02-20 18:03:55 +0800272 view.getPaddingRight(), view.getPaddingBottom());
Santiago Etchebehere35891ea2019-07-26 15:21:42 -0700273 // Consume only the top inset (status bar), to let other content in the Activity consume
274 // the nav bar (ie, by using "fitSystemWindows")
275 if (BuildCompat.isAtLeastQ()) {
276 WindowInsets.Builder builder = new WindowInsets.Builder(windowInsets);
277 builder.setSystemWindowInsets(Insets.of(windowInsets.getSystemWindowInsetLeft(),
278 0, windowInsets.getStableInsetRight(),
279 windowInsets.getSystemWindowInsetBottom()));
280 return builder.build();
281 } else {
282 return windowInsets.replaceSystemWindowInsets(
283 windowInsets.getSystemWindowInsetLeft(),
284 0, windowInsets.getStableInsetRight(),
285 windowInsets.getSystemWindowInsetBottom());
286 }
287 });
Jon Miranda16ea1b12017-12-12 14:52:48 -0800288
289 // Set toolbar as the action bar.
290 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
291 setSupportActionBar(toolbar);
292
293 FragmentManager fm = getSupportFragmentManager();
294 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
295
Jon Miranda16ea1b12017-12-12 14:52:48 -0800296 if (fragment == null) {
297 // App launch specific logic: log the "app launched" event and set up daily logging.
298 mUserEventLogger.logAppLaunched();
Kunhung Li166842e2020-05-13 19:19:06 +0800299 mWallpaperPreferences.incrementAppLaunched();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800300 DailyLoggingAlarmScheduler.setAlarm(getApplicationContext());
301
Santiago Etchebehereaa35e6e2019-01-25 10:30:11 -0800302 CategoryFragment newFragment = CategoryFragment.newInstance(
303 getString(R.string.wallpaper_app_name));
Jon Miranda16ea1b12017-12-12 14:52:48 -0800304 fm.beginTransaction()
305 .add(R.id.fragment_container, newFragment)
306 .commit();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800307 }
Jon Miranda16ea1b12017-12-12 14:52:48 -0800308 }
309
310 private void initializeDesktop(Bundle savedInstanceState) {
311 setContentView(R.layout.activity_top_level_desktop);
312
313 mBottomSheet = (LinearLayout) findViewById(R.id.bottom_sheet);
314 mCurrentWallpaperImage = (ImageView) mBottomSheet.findViewById(R.id.current_wallpaper_image);
315 mCurrentWallpaperImage.getLayoutParams().width = getSingleWallpaperImageWidthPx();
316
317 mCurrentWallpaperPresentationMode =
318 (TextView) mBottomSheet.findViewById(R.id.current_wallpaper_presentation_mode);
319 mCurrentWallpaperTitle = (TextView) findViewById(R.id.current_wallpaper_title);
320 mCurrentWallpaperSubtitle = (TextView) findViewById(R.id.current_wallpaper_subtitle);
321 mCurrentWallpaperExploreButton = (Button) findViewById(
322 R.id.current_wallpaper_explore_button);
323 mCurrentWallpaperSkipWallpaperButton = (Button) findViewById(
324 R.id.current_wallpaper_skip_wallpaper_button);
325 mFragmentContainer = (FrameLayout) findViewById(R.id.fragment_container);
326 mLoadingIndicatorContainer = (FrameLayout) findViewById(R.id.loading_indicator_container);
327 mWallpaperPositionOptions = (LinearLayout) findViewById(
328 R.id.desktop_wallpaper_position_options);
329
330 final TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
331 tabLayout.addOnTabSelectedListener(new OnTabSelectedListener() {
332 @Override
333 public void onTabSelected(Tab tab) {
334 Category category = (Category) tab.getTag();
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800335 showCategoryDesktop(category.getCollectionId());
Jon Miranda16ea1b12017-12-12 14:52:48 -0800336 mLastSelectedCategoryTabIndex = tabLayout.getSelectedTabPosition();
337 }
338
339 @Override
340 public void onTabUnselected(Tab tab) {
341 }
342
343 @Override
344 public void onTabReselected(Tab tab) {
345 Category category = (Category) tab.getTag();
346 // If offline, "My photos" may be the only visible category. In this case we want to allow
347 // re-selection so user can still select a photo as wallpaper while offline.
348 if (!category.isEnumerable()) {
349 onTabSelected(tab);
350 }
351 }
352 });
353
354 FragmentManager fm = getSupportFragmentManager();
355 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
356
357 if (fragment == null) {
358 // App launch specific logic: log the "app launched" event and set up daily logging.
359 mUserEventLogger.logAppLaunched();
Kunhung Li166842e2020-05-13 19:19:06 +0800360 mWallpaperPreferences.incrementAppLaunched();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800361 DailyLoggingAlarmScheduler.setAlarm(getApplicationContext());
362 }
363
364 mNetworkStatusListener = new NetworkStatusNotifier.Listener() {
365 @Override
366 public void onNetworkChanged(@NetworkStatus int networkStatus) {
367 initializeDesktopBasedOnNetwork(networkStatus, savedInstanceState);
368 }
369 };
370 // Upon registering a listener, the onNetworkChanged method is immediately called with the
371 // initial network status.
372 mNetworkStatusNotifier.registerListener(mNetworkStatusListener);
373 }
374
375 private void initializeDesktopBasedOnNetwork(@NetworkStatus int networkStatus,
376 Bundle savedInstanceState) {
377 if (networkStatus == NetworkStatusNotifier.NETWORK_CONNECTED) {
378 initializeDesktopOnline(savedInstanceState);
379 } else {
380 initializeDesktopOffline();
381 }
382 }
383
384 private void initializeDesktopOnline(Bundle savedInstanceState) {
385 FragmentManager fm = getSupportFragmentManager();
386 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
387
388 // Require a category refresh if this is the first load of the app or if the app is now
389 // returning online after having been offline.
390 boolean forceCategoryRefresh = fragment == null || fragment instanceof OfflineDesktopFragment;
391
392 if (fragment != null) {
393 fm.beginTransaction()
394 .remove(fragment)
395 .commit();
396 }
397
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800398 mLastSelectedCategoryTabIndex = savedInstanceState != null
Jon Miranda16ea1b12017-12-12 14:52:48 -0800399 ? savedInstanceState.getInt(KEY_SELECTED_CATEGORY_TAB) : -1;
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800400 mDelegate.populateCategories(forceCategoryRefresh);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800401
402 setDesktopLoading(true);
403 setUpBottomSheet();
404 refreshCurrentWallpapers(null /* refreshListener */);
405 }
406
407 private void initializeDesktopOffline() {
408 FragmentManager fm = getSupportFragmentManager();
409 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
410
411 if (fragment != null) {
412 fm.beginTransaction()
413 .remove(fragment)
414 .commit();
415 }
416 OfflineDesktopFragment newFragment = new OfflineDesktopFragment();
417 fm.beginTransaction()
418 .add(R.id.fragment_container, newFragment)
419 .commit();
420
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800421 // Reset the last selected category tab index to ensure the app doesn't try to reselect a
422 // tab for a category not yet repopulated.
Jon Miranda16ea1b12017-12-12 14:52:48 -0800423 mLastSelectedCategoryTabIndex = -1;
424
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800425 mDelegate.populateCategories(true /* forceCategoryRefresh */);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800426
427 setDesktopLoading(false);
428 setCurrentWallpapersExpanded(false);
429 }
430
431 /**
432 * Sets the status of the loading indicator overlay in desktop mode.
433 *
434 * @param loading Whether an indeterminate loading indicator is displayed in place of the main
435 * fragment.
436 */
437 private void setDesktopLoading(boolean loading) {
438 if (loading) {
439 mLoadingIndicatorContainer.setVisibility(View.VISIBLE);
440 mFragmentContainer.setVisibility(View.GONE);
441 } else {
442 mLoadingIndicatorContainer.setVisibility(View.GONE);
443 mFragmentContainer.setVisibility(View.VISIBLE);
444 }
445 }
446
447 /**
448 * Returns the width (in physical px) to use for the "currently set wallpaper" thumbnail.
449 */
450 private int getSingleWallpaperImageWidthPx() {
chihhangchuangc8442a72020-05-07 14:26:32 +0800451 final float screenAspectRatio =
452 ScreenSizeCalculator.getInstance().getScreenAspectRatio(this);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800453
454 int height = getResources().getDimensionPixelSize(
455 R.dimen.current_wallpaper_bottom_sheet_thumb_height);
chihhangchuangc8442a72020-05-07 14:26:32 +0800456 return (int) (height / screenAspectRatio);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800457 }
458
459 /**
460 * Enables and populates the "Currently set" wallpaper BottomSheet.
461 */
462 private void setUpBottomSheet() {
463 mBottomSheet.setVisibility(View.VISIBLE);
464
Jon Miranda16ea1b12017-12-12 14:52:48 -0800465 if (Flags.skipDailyWallpaperButtonEnabled) {
466 // Add "next" icon to the Next Wallpaper button
467 Drawable nextWallpaperButtonDrawable = getResources().getDrawable(
Santiago Etchebehered24506c2018-04-05 17:02:42 -0700468 R.drawable.ic_refresh_18px);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800469
470 // This Drawable's state is shared across the app, so make a copy of it before applying a
471 // color tint as not to affect other clients elsewhere in the app.
472 nextWallpaperButtonDrawable =
473 nextWallpaperButtonDrawable.getConstantState().newDrawable().mutate();
474 // Color the "compass" icon with the accent color.
475 nextWallpaperButtonDrawable.setColorFilter(
476 getResources().getColor(R.color.accent_color), Mode.SRC_IN);
477 ButtonDrawableSetterCompat.setDrawableToButtonStart(
478 mCurrentWallpaperSkipWallpaperButton, nextWallpaperButtonDrawable);
479 }
480
481 final BottomSheetBehavior<LinearLayout> bottomSheetBehavior =
482 BottomSheetBehavior.from(mBottomSheet);
483 bottomSheetBehavior.setBottomSheetCallback(new BottomSheetCallback() {
484 @Override
485 public void onStateChanged(@NonNull View view, int i) {
486 }
487
488 @Override
489 public void onSlide(@NonNull View view, float slideOffset) {
490 float alpha;
491 if (slideOffset >= 0) {
492 alpha = slideOffset;
493 } else {
494 alpha = 1f - slideOffset;
495 }
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800496 LinearLayout bottomSheetContents = findViewById(R.id.bottom_sheet_contents);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800497 bottomSheetContents.setAlpha(alpha);
498 }
499 });
500 }
501
502 /**
503 * Enables a test mode of operation -- in which certain UI features are disabled to allow for
504 * UI tests to run correctly. Works around issue in ProgressDialog currently where the dialog
505 * constantly keeps the UI thread alive and blocks a test forever.
506 */
507 void setTestingMode(boolean testingMode) {
508 mTestingMode = testingMode;
509 }
510
511 /**
512 * Obtains the {@link WallpaperInfo} object(s) representing the wallpaper(s) currently set to the
513 * device from the {@link CurrentWallpaperInfoFactory} and displays them in the BottomSheet.
514 */
515 @Override
516 public void refreshCurrentWallpapers(@Nullable RefreshListener refreshListener) {
517 final Injector injector = InjectorProvider.getInjector();
518 final Context appContext = getApplicationContext();
519
520 CurrentWallpaperInfoFactory factory = injector.getCurrentWallpaperFactory(this);
521 factory.createCurrentWallpaperInfos(new WallpaperInfoCallback() {
522 @Override
523 public void onWallpaperInfoCreated(
524 final WallpaperInfo homeWallpaper,
525 @Nullable final WallpaperInfo lockWallpaper,
526 @PresentationMode final int presentationMode) {
527
528 if (isDestroyed()) {
529 return;
530 }
531
532 // Fetch the home wallpaper's thumbnail asset asynchronously to work around expensive
533 // method call to WallpaperManager#getWallpaperFile made from the CurrentWallpaperInfoVN
534 // getAsset() method.
535 AssetReceiver assetReceiver = (Asset thumbAsset) -> {
536 if (isDestroyed()) {
537 return;
538 }
539
540 homeWallpaper.getThumbAsset(appContext).loadDrawableWithTransition(
541 TopLevelPickerActivity.this,
542 mCurrentWallpaperImage,
543 200 /* transitionDurationMillis */,
544 () -> {
545 if (refreshListener != null) {
546 refreshListener.onCurrentWallpaperRefreshed();
547 }
548 },
549 Color.TRANSPARENT);
550 };
551 new FetchThumbAssetTask(appContext, homeWallpaper, assetReceiver).executeOnExecutor(
552 AsyncTask.THREAD_POOL_EXECUTOR);
553
554 mCurrentWallpaperPresentationMode.setText(
555 AttributionFormatter.getHumanReadableWallpaperPresentationMode(
556 TopLevelPickerActivity.this, presentationMode));
557
558 List<String> attributions = homeWallpaper.getAttributions(appContext);
559 if (attributions.size() > 0 && attributions.get(0) != null) {
560 mCurrentWallpaperTitle.setText(attributions.get(0));
561 }
562
563 mCurrentWallpaperSubtitle.setText(
564 AttributionFormatter.formatWallpaperSubtitle(appContext, homeWallpaper));
565
566 final String actionUrl = homeWallpaper.getActionUrl(appContext);
567 if (actionUrl != null && !actionUrl.isEmpty()) {
568 Uri exploreUri = Uri.parse(actionUrl);
569
570 ExploreIntentChecker intentChecker = injector.getExploreIntentChecker(appContext);
571 intentChecker.fetchValidActionViewIntent(exploreUri, (@Nullable Intent exploreIntent) -> {
572 if (exploreIntent != null && !isDestroyed()) {
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700573 // Set the icon for the button
574 Drawable exploreButtonDrawable = getResources().getDrawable(
Santiago Etchebeheree0810d02018-05-10 17:39:40 -0700575 homeWallpaper.getActionIconRes(appContext));
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700576
577 // This Drawable's state is shared across the app, so make a copy of it
578 // before applying a color tint as not to affect other clients elsewhere
579 // in the app.
580 exploreButtonDrawable = exploreButtonDrawable.getConstantState()
581 .newDrawable().mutate();
582 // Color the "compass" icon with the accent color.
583 exploreButtonDrawable.setColorFilter(
584 getResources().getColor(R.color.accent_color), Mode.SRC_IN);
585
586 ButtonDrawableSetterCompat.setDrawableToButtonStart(
587 mCurrentWallpaperExploreButton, exploreButtonDrawable);
588 mCurrentWallpaperExploreButton.setText(getString(
Santiago Etchebeheree0810d02018-05-10 17:39:40 -0700589 homeWallpaper.getActionLabelRes(appContext)));
Jon Miranda16ea1b12017-12-12 14:52:48 -0800590 mCurrentWallpaperExploreButton.setVisibility(View.VISIBLE);
591 mCurrentWallpaperExploreButton.setOnClickListener(new OnClickListener() {
592 @Override
593 public void onClick(View v) {
Santiago Etchebeherece5613f2018-06-01 13:22:47 -0700594 mUserEventLogger.logActionClicked(
595 homeWallpaper.getCollectionId(appContext),
596 homeWallpaper.getActionLabelRes(appContext));
Jon Miranda16ea1b12017-12-12 14:52:48 -0800597 startActivity(exploreIntent);
598 }
599 });
600 }
601 });
602 } else {
603 mCurrentWallpaperExploreButton.setVisibility(View.GONE);
604 }
605
606 // Hide the wallpaper position options UI if the current home wallpaper is not from
607 // "my photos".
608 String homeCollectionId = homeWallpaper.getCollectionId(TopLevelPickerActivity.this);
609 if (mWallpaperPositionOptions != null
610 && homeCollectionId != null // May be null if app is being used for the first time.
611 && !homeCollectionId.equals(getString(R.string.image_wallpaper_collection_id))) {
612 mWallpaperPositionOptions.setVisibility(View.GONE);
613 }
614
615 boolean showSkipWallpaperButton = Flags.skipDailyWallpaperButtonEnabled
616 && presentationMode == WallpaperPreferences.PRESENTATION_MODE_ROTATING;
617 if (showSkipWallpaperButton) {
618 mCurrentWallpaperSkipWallpaperButton.setVisibility(View.VISIBLE);
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800619 mCurrentWallpaperSkipWallpaperButton.setOnClickListener(
620 v -> refreshDailyWallpaper());
Jon Miranda16ea1b12017-12-12 14:52:48 -0800621 } else {
622 mCurrentWallpaperSkipWallpaperButton.setVisibility(View.GONE);
623 }
624
625 if (refreshListener != null) {
626 refreshListener.onCurrentWallpaperRefreshed();
627 }
628 }
629 }, true /* forceRefresh */);
630 }
631
632 @Override
633 public void onSaveInstanceState(Bundle savedInstanceState) {
634 FormFactorChecker formFactorChecker = InjectorProvider.getInjector().getFormFactorChecker(this);
635 if (formFactorChecker.getFormFactor() == FormFactorChecker.FORM_FACTOR_DESKTOP) {
636 TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
637
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800638 // tabLayout is only present when the main IndividualPickerFragment is present (as
639 // opposed to
Jon Miranda16ea1b12017-12-12 14:52:48 -0800640 // the WallpaperDisabledFragment), so need this null check.
641 if (tabLayout != null) {
642 savedInstanceState.putInt(KEY_SELECTED_CATEGORY_TAB, tabLayout.getSelectedTabPosition());
643 }
644 }
645
646 super.onSaveInstanceState(savedInstanceState);
647 }
648
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800649 @Override
Santiago Etchebehere1ee76a22018-05-15 15:02:24 -0700650 @Nullable
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800651 public CategoryFragment getCategoryFragment() {
652 if (mDelegate.getFormFactor() != FormFactorChecker.FORM_FACTOR_MOBILE) {
Santiago Etchebehere1ee76a22018-05-15 15:02:24 -0700653 return null;
654 }
655 FragmentManager fm = getSupportFragmentManager();
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800656 return (CategoryFragment) fm.findFragmentById(R.id.fragment_container);
Santiago Etchebehere1ee76a22018-05-15 15:02:24 -0700657 }
658
Jon Miranda16ea1b12017-12-12 14:52:48 -0800659 /**
660 * Populates the category tabs on DESKTOP form factor.
661 *
662 * @param selectedTabPosition The position of the tab to show as selected, or -1 if no particular
663 * tab should be selected (in which case: the tab of the category for the currently set
664 * wallpaper will be selected if enumerable; if not, the first enumerable category's tab will
665 * be selected).
666 */
667 private void populateCategoryTabs(int selectedTabPosition) {
668 final TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
669 tabLayout.removeAllTabs();
670
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800671 String currentlySetCollectionId = mDelegate.getPreferences().getHomeWallpaperCollectionId();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800672
673 Tab tabToSelect = null;
674 Tab firstEnumerableCategoryTab = null;
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800675 for (int i = 0; i < mDelegate.getCategoryProvider().getSize(); i++) {
676 Category category = mDelegate.getCategoryProvider().getCategory(i);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800677
678 Tab tab = tabLayout.newTab();
679 tab.setText(category.getTitle());
680 tab.setTag(category);
681 tabLayout.addTab(tab, false /* setSelected */);
682
683 if (firstEnumerableCategoryTab == null && category.isEnumerable()) {
684 firstEnumerableCategoryTab = tab;
685 }
686
687 boolean shouldSelectTab = (i == selectedTabPosition)
688 || (selectedTabPosition == -1
689 && tabToSelect == null
690 && category.isEnumerable()
691 && currentlySetCollectionId != null
692 && currentlySetCollectionId.equals(category.getCollectionId()));
693
694 if (shouldSelectTab) {
695 tabToSelect = tab;
696 }
697 }
698
699 // If the above loop did not identify a specific tab to select, then just select the tab for
700 // the first enumerable category.
701 if (tabToSelect == null) {
702 tabToSelect = firstEnumerableCategoryTab;
703 }
704
705 // There may be no enumerable tabs (e.g., offline case), so we need to null-check again.
706 if (tabToSelect != null) {
707 tabToSelect.select();
708 }
709 }
710
711 /**
712 * Refreshes the current wallpaper in a daily wallpaper rotation.
713 */
714 private void refreshDailyWallpaper() {
715 // ProgressDialog endlessly updates the UI thread, keeping it from going idle which therefore
716 // causes Espresso to hang once the dialog is shown.
717 if (!mTestingMode) {
718 int themeResId;
719 if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
720 themeResId = R.style.ProgressDialogThemePreL;
721 } else {
722 themeResId = R.style.LightDialogTheme;
723 }
724 mRefreshWallpaperProgressDialog = new ProgressDialog(this, themeResId);
725 mRefreshWallpaperProgressDialog.setTitle(null);
726 mRefreshWallpaperProgressDialog.setMessage(
727 getResources().getString(R.string.refreshing_daily_wallpaper_dialog_message));
728 mRefreshWallpaperProgressDialog.setIndeterminate(true);
729 mRefreshWallpaperProgressDialog.show();
730 }
731
732 WallpaperRotationRefresher wallpaperRotationRefresher =
733 InjectorProvider.getInjector().getWallpaperRotationRefresher();
734 wallpaperRotationRefresher.refreshWallpaper(this, new Listener() {
735 @Override
736 public void onRefreshed() {
737 if (isDestroyed()) {
738 return;
739 }
740
741 if (mRefreshWallpaperProgressDialog != null) {
742 mRefreshWallpaperProgressDialog.dismiss();
743 }
744
745 refreshCurrentWallpapers(null /* refreshListener */);
746 }
747
748 @Override
749 public void onError() {
750 if (mRefreshWallpaperProgressDialog != null) {
751 mRefreshWallpaperProgressDialog.dismiss();
752 }
753
754 AlertDialog errorDialog = new AlertDialog.Builder(
755 TopLevelPickerActivity.this, R.style.LightDialogTheme)
756 .setMessage(R.string.refresh_daily_wallpaper_failed_message)
757 .setPositiveButton(android.R.string.ok, null /* onClickListener */)
758 .create();
759 errorDialog.show();
760 }
761 });
762 }
763
764 @Override
765 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
766 super.onActivityResult(requestCode, resultCode, data);
767
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800768 if (requestCode == WallpaperPickerDelegate.SHOW_CATEGORY_REQUEST_CODE
769 && resultCode == Activity.RESULT_OK) {
Santiago Etchebeheree5e05842019-02-13 16:58:07 -0800770 if (mDelegate.getFormFactor() == FormFactorChecker.FORM_FACTOR_DESKTOP) {
771 Uri imageUri = (data == null) ? null : data.getData();
772 if (imageUri != null) {
773 // User selected an image from the system picker, so launch the preview for that
774 // image.
775 ImageWallpaperInfo imageWallpaper = new ImageWallpaperInfo(imageUri);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800776 setCustomPhotoWallpaper(imageWallpaper);
777 return;
778 }
Jon Miranda16ea1b12017-12-12 14:52:48 -0800779 }
Santiago Etchebeheree5e05842019-02-13 16:58:07 -0800780 }
781 if (mDelegate.handleActivityResult(requestCode, resultCode, data)) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800782 finishActivityWithResultOk();
783 }
784 }
785
786 /**
787 * Shows the view-only preview activity for the given wallpaper.
788 */
Ching-Sung Lief59efa2020-06-05 22:41:43 +0800789 public void showViewOnlyPreview(WallpaperInfo wallpaperInfo, boolean isViewAsHome) {
790 mDelegate.showViewOnlyPreview(wallpaperInfo, isViewAsHome);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800791 }
792
793 @Override
Chuck Liaoa63f1bf2020-06-11 01:35:42 +0800794 public void show(String collectionId) {
795 mDelegate.show(collectionId);
796 }
797
798 @Override
Chuck Liaoaee30432020-06-23 01:17:05 +0800799 public boolean isNavigationTabsContained() {
800 return false;
801 }
802
803 @Override
Chuck Liaof6b4b192020-08-07 02:31:32 +0800804 public void fetchCategories() {
805 mDelegate.initialize(!mDelegate.getCategoryProvider().isCategoriesFetched());
806 }
807
808 @Override
Jon Miranda16ea1b12017-12-12 14:52:48 -0800809 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
810 @NonNull int[] grantResults) {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800811 mDelegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800812 }
813
Jon Miranda16ea1b12017-12-12 14:52:48 -0800814 private void reselectLastTab() {
815 TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
816
817 // In the offline case, "My photos" could be the only category. Thus we need this check --
818 // to ensure that we don't try to select the "previously selected" category which was -1.
819 if (mLastSelectedCategoryTabIndex > -1) {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800820 Tab tabToSelect = tabLayout.getTabAt(
821 mLastSelectedCategoryTabIndex);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800822 if (((Category) tabToSelect.getTag()).isEnumerable()) {
823 tabToSelect.select();
824 }
825 }
826 }
827
Jon Miranda16ea1b12017-12-12 14:52:48 -0800828 private void showCategoryDesktop(String collectionId) {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800829 Category category = mDelegate.findCategoryForCollectionId(collectionId);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800830 if (category == null) {
831 return;
832 }
833
834 if (category.isEnumerable()) {
835 // Replace contained IndividualPickerFragment with a new instance for the given category.
836 final FragmentManager fm = getSupportFragmentManager();
837 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
838 if (fragment != null) {
839 fm.beginTransaction()
840 .remove(fragment)
841 .commit();
842 }
Ching-Sung Li31fbe5e2019-01-23 19:36:24 +0800843 Injector injector = InjectorProvider.getInjector();
844 IndividualPickerFragment newFragment = injector.getIndividualPickerFragment(
845 collectionId);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800846 fm.beginTransaction()
847 .add(R.id.fragment_container, newFragment)
848 .commit();
849 newFragment.setCurrentWallpaperBottomSheetPresenter(this);
850 newFragment.setWallpapersUiContainer(this);
851 } else {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800852 category.show(this, mDelegate.getPickerIntentFactory(),
853 WallpaperPickerDelegate.SHOW_CATEGORY_REQUEST_CODE);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800854
855 // Need to select the tab here in case we are coming back from a "My photos" in which case
856 // the tab would have been set to "My photos" while viewing a regular image category.
857 reselectLastTab();
858 }
859 }
860
861 private void finishActivityWithResultOk() {
862 overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
863 setResult(Activity.RESULT_OK);
864 finish();
865 }
866
Jon Miranda16ea1b12017-12-12 14:52:48 -0800867 @Override
868 public void setCurrentWallpapersExpanded(boolean expanded) {
869 final BottomSheetBehavior<LinearLayout> bottomSheetBehavior =
870 BottomSheetBehavior.from(mBottomSheet);
871 bottomSheetBehavior.setState(
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800872 expanded ? BottomSheetBehavior.STATE_EXPANDED
873 : BottomSheetBehavior.STATE_COLLAPSED);
874 }
875
876 @Override
877 public void doneFetchingCategories() {
878 populateCategoryTabs(mLastSelectedCategoryTabIndex);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800879 }
880
881 @Override
882 public void onWallpapersReady() {
883 setDesktopLoading(false);
884 setCurrentWallpapersExpanded(true);
885 }
886
887 @Override
Santiago Etchebeherefab49612019-01-15 12:22:42 -0800888 public MyPhotosStarter getMyPhotosStarter() {
889 return this;
890 }
891
892 @Override
Jon Miranda16ea1b12017-12-12 14:52:48 -0800893 public void onClickTryAgain(@Destination int unused) {
894 // Retry the set wallpaper operation with the default center-crop setting.
895 if (mPendingSetWallpaperInfo != null) {
896 setCustomPhotoWallpaper(mPendingSetWallpaperInfo);
897 }
898 }
899
900 /**
901 * Sets the provides wallpaper to the device with center-cropped and scaled to fit the device's
902 * default display.
903 */
904 private void setCustomPhotoWallpaper(final WallpaperInfo wallpaper) {
905 // Save this WallpaperInfo so we can retry this operation later if it fails.
906 mPendingSetWallpaperInfo = wallpaper;
907
908 showSettingWallpaperProgressDialog();
909
910 mWallpaperPersister.setIndividualWallpaperWithPosition(this, wallpaper,
911 WallpaperPersister.WALLPAPER_POSITION_CENTER_CROP, new SetWallpaperCallback() {
912 @Override
“Chuckffd832c2020-03-22 02:15:58 +0800913 public void onSuccess(WallpaperInfo wallpaperInfo) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800914 dismissSettingWallpaperProgressDialog();
915 refreshCurrentWallpapers(null /* refreshListener */);
916
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800917 mDelegate.getPreferences().setPendingWallpaperSetStatus(
Jon Miranda16ea1b12017-12-12 14:52:48 -0800918 WallpaperPreferences.WALLPAPER_SET_NOT_PENDING);
919 mUserEventLogger.logWallpaperSet(
920 wallpaper.getCollectionId(getApplicationContext()),
921 wallpaper.getWallpaperId());
922 mUserEventLogger.logWallpaperSetResult(UserEventLogger.WALLPAPER_SET_RESULT_SUCCESS);
923
924 // The user may have closed the activity before the set wallpaper operation completed.
925 if (isDestroyed()) {
926 return;
927 }
928
929 // Show the wallpaper crop option selector and bind click event handlers.
930 mWallpaperPositionOptions.setVisibility(View.VISIBLE);
931
932 mWasCustomPhotoWallpaperSet = true;
933 mCustomPhotoWallpaperPosition = WallpaperPersister.WALLPAPER_POSITION_CENTER_CROP;
934
935 initializeWallpaperPositionOptionClickHandlers(wallpaper);
936 }
937
938 @Override
939 public void onError(Throwable throwable) {
940 dismissSettingWallpaperProgressDialog();
941 showSetWallpaperErrorDialog();
942
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800943 mDelegate.getPreferences().setPendingWallpaperSetStatus(
Jon Miranda16ea1b12017-12-12 14:52:48 -0800944 WallpaperPreferences.WALLPAPER_SET_NOT_PENDING);
945 mUserEventLogger.logWallpaperSetResult(
946 UserEventLogger.WALLPAPER_SET_RESULT_FAILURE);
947 @WallpaperSetFailureReason int failureReason = ThrowableAnalyzer.isOOM(throwable)
948 ? UserEventLogger.WALLPAPER_SET_FAILURE_REASON_OOM
949 : UserEventLogger.WALLPAPER_SET_FAILURE_REASON_OTHER;
950 mUserEventLogger.logWallpaperSetFailureReason(failureReason);
951 Log.e(TAG, "Unable to set wallpaper from 'my photos'.");
952 }
953 });
954 }
955
956 /**
957 * Initializes the wallpaper position button click handlers to change the way the provided
958 * wallpaper is set to the device.
959 */
960 private void initializeWallpaperPositionOptionClickHandlers(final WallpaperInfo wallpaperInfo) {
961 Button centerCropOptionBtn = (Button) findViewById(R.id.wallpaper_position_option_center_crop);
962 Button stretchOptionBtn = (Button) findViewById(R.id.wallpaper_position_option_stretched);
963 Button centerOptionBtn = (Button) findViewById(R.id.wallpaper_position_option_center);
964
965 // The "center crop" wallpaper position button is selected by default.
966 setCenterCropWallpaperPositionButtonSelected(centerCropOptionBtn, true /* isSelected */);
967 centerCropOptionBtn.setOnClickListener(new OnClickListener() {
968 @Override
969 public void onClick(View view) {
970 mWallpaperPersister.setIndividualWallpaperWithPosition(TopLevelPickerActivity.this,
971 wallpaperInfo, WallpaperPersister.WALLPAPER_POSITION_CENTER_CROP,
972 new SetWallpaperCallback() {
973 @Override
“Chuckffd832c2020-03-22 02:15:58 +0800974 public void onSuccess(WallpaperInfo wallpaperInfo) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800975 // The user may have closed the activity before the set wallpaper operation
976 // completed.
977 if (isDestroyed()) {
978 return;
979 }
980
981 refreshCurrentWallpapers(null /* refreshListener */);
982
983 setCenterCropWallpaperPositionButtonSelected(
984 centerCropOptionBtn, true /* isSelected */);
985 setCenterWallpaperPositionButtonSelected(centerOptionBtn, false /* isSelected */);
986 setStretchWallpaperPositionButtonSelected(stretchOptionBtn, false /* isSelected */);
987
988 mCustomPhotoWallpaperPosition = WallpaperPersister.WALLPAPER_POSITION_CENTER_CROP;
989 }
990
991 @Override
992 public void onError(@Nullable Throwable throwable) {
993 // no-op
994 }
995 });
996 }
997 });
998
999 // "Stretch" is not selected by default.
1000 setStretchWallpaperPositionButtonSelected(stretchOptionBtn, false /* isSelected */);
1001 stretchOptionBtn.setOnClickListener(new OnClickListener() {
1002 @Override
1003 public void onClick(View view) {
1004 mWallpaperPersister.setIndividualWallpaperWithPosition(TopLevelPickerActivity.this,
1005 wallpaperInfo, WallpaperPersister.WALLPAPER_POSITION_STRETCH,
1006 new SetWallpaperCallback() {
1007 @Override
“Chuckffd832c2020-03-22 02:15:58 +08001008 public void onSuccess(WallpaperInfo wallpaperInfo) {
Jon Miranda16ea1b12017-12-12 14:52:48 -08001009 // The user may have closed the activity before the set wallpaper operation
1010 // completed.
1011 if (isDestroyed()) {
1012 return;
1013 }
1014
1015 refreshCurrentWallpapers(null /* refreshListener */);
1016
1017 setStretchWallpaperPositionButtonSelected(stretchOptionBtn, true /* isSelected */);
1018 setCenterCropWallpaperPositionButtonSelected(
1019 centerCropOptionBtn, false /* isSelected */);
1020 setCenterWallpaperPositionButtonSelected(centerOptionBtn, false /* isSelected */);
1021
1022 mCustomPhotoWallpaperPosition = WallpaperPersister.WALLPAPER_POSITION_STRETCH;
1023 }
1024
1025 @Override
1026 public void onError(@Nullable Throwable throwable) {
1027 // no-op
1028 }
1029 });
1030 }
1031 });
1032
1033 // "Center" is not selected by default.
1034 setCenterWallpaperPositionButtonSelected(centerOptionBtn, false /* isSelected */);
1035 centerOptionBtn.setOnClickListener(new OnClickListener() {
1036 @Override
1037 public void onClick(View view) {
1038 mWallpaperPersister.setIndividualWallpaperWithPosition(TopLevelPickerActivity.this,
1039 wallpaperInfo, WallpaperPersister.WALLPAPER_POSITION_CENTER,
1040 new SetWallpaperCallback() {
1041 @Override
“Chuckffd832c2020-03-22 02:15:58 +08001042 public void onSuccess(WallpaperInfo wallpaperInfo) {
Jon Miranda16ea1b12017-12-12 14:52:48 -08001043 // The user may have closed the activity before the set wallpaper operation
1044 // completed.
1045 if (isDestroyed()) {
1046 return;
1047 }
1048
1049 refreshCurrentWallpapers(null /* refreshListener */);
1050
1051 setCenterWallpaperPositionButtonSelected(centerOptionBtn, true /* isSelected */);
1052 setCenterCropWallpaperPositionButtonSelected(
1053 centerCropOptionBtn, false /* isSelected */);
1054 setStretchWallpaperPositionButtonSelected(stretchOptionBtn, false /* isSelected */);
1055
1056 mCustomPhotoWallpaperPosition = WallpaperPersister.WALLPAPER_POSITION_CENTER;
1057 }
1058
1059 @Override
1060 public void onError(@Nullable Throwable throwable) {
1061 // no-op
1062 }
1063 });
1064 }
1065 });
1066 }
1067
1068 private void setCenterWallpaperPositionButtonSelected(Button button, boolean isSelected) {
1069 int drawableId = isSelected ? R.drawable.center_blue : R.drawable.center_grey;
1070 ButtonDrawableSetterCompat.setDrawableToButtonStart(button, getDrawable(drawableId));
1071 button.setTextColor(getColor(getTextColorIdForWallpaperPositionButton(isSelected)));
1072 }
1073
1074 private void setCenterCropWallpaperPositionButtonSelected(Button button, boolean isSelected) {
1075 int drawableId = isSelected ? R.drawable.center_crop_blue : R.drawable.center_crop_grey;
1076 ButtonDrawableSetterCompat.setDrawableToButtonStart(button, getDrawable(drawableId));
1077 button.setTextColor(getColor(getTextColorIdForWallpaperPositionButton(isSelected)));
1078 }
1079
1080 private void setStretchWallpaperPositionButtonSelected(Button button, boolean isSelected) {
1081 int drawableId = isSelected ? R.drawable.stretch_blue : R.drawable.stretch_grey;
1082 ButtonDrawableSetterCompat.setDrawableToButtonStart(button, getDrawable(drawableId));
1083 button.setTextColor(getColor(getTextColorIdForWallpaperPositionButton(isSelected)));
1084 }
1085
1086 private void showSettingWallpaperProgressDialog() {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -08001087 // ProgressDialog endlessly updates the UI thread, keeping it from going idle which
1088 // therefore causes Espresso to hang once the dialog is shown.
Jon Miranda16ea1b12017-12-12 14:52:48 -08001089 if (!mTestingMode) {
1090 int themeResId;
1091 if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
1092 themeResId = R.style.ProgressDialogThemePreL;
1093 } else {
1094 themeResId = R.style.LightDialogTheme;
1095 }
1096 mSetWallpaperProgressDialog = new ProgressDialog(this, themeResId);
1097 mSetWallpaperProgressDialog.setTitle(null);
1098 mSetWallpaperProgressDialog.setMessage(
1099 getResources().getString(R.string.set_wallpaper_progress_message));
1100 mSetWallpaperProgressDialog.setIndeterminate(true);
1101 mSetWallpaperProgressDialog.show();
1102 }
1103 }
1104
1105 private void dismissSettingWallpaperProgressDialog() {
1106 if (mSetWallpaperProgressDialog != null) {
1107 mSetWallpaperProgressDialog.dismiss();
1108 }
1109 }
1110
1111 private void showSetWallpaperErrorDialog() {
1112 SetWallpaperErrorDialogFragment dialogFragment = SetWallpaperErrorDialogFragment.newInstance(
1113 R.string.set_wallpaper_error_message, WallpaperPersister.DEST_BOTH);
1114
1115 if (isSafeToCommitFragmentTransaction()) {
1116 dialogFragment.show(getSupportFragmentManager(), TAG_SET_WALLPAPER_ERROR_DIALOG_FRAGMENT);
1117 } else {
1118 mStagedSetWallpaperErrorDialogFragment = dialogFragment;
1119 }
1120 }
1121
chihhangchuang3efb6832020-04-17 02:06:25 +08001122 @Override
1123 public BottomActionBar getBottomActionBar() {
1124 return findViewById(R.id.bottom_actionbar);
1125 }
1126
Jon Miranda16ea1b12017-12-12 14:52:48 -08001127 private interface AssetReceiver {
1128 void onAssetReceived(Asset asset);
1129 }
1130
1131 /**
1132 * An AsyncTask for asynchronously fetching the thumbnail asset for a given WallpaperInfo.
1133 * Used to work around expensive method call to WallpaperManager#getWallpaperFile made from the
1134 * CurrentWallpaperInfoVN getAsset() method.
1135 */
1136 private static class FetchThumbAssetTask extends AsyncTask<Void, Void, Asset> {
1137 private Context mAppContext;
1138 private WallpaperInfo mWallpaperInfo;
1139 private AssetReceiver mReceiver;
1140
1141 public FetchThumbAssetTask(Context appContext, WallpaperInfo wallpaperInfo,
1142 AssetReceiver receiver) {
1143 mAppContext = appContext;
1144 mWallpaperInfo = wallpaperInfo;
1145 mReceiver = receiver;
1146 }
1147
1148 @Override
1149 protected Asset doInBackground(Void... params) {
1150 return mWallpaperInfo.getThumbAsset(mAppContext);
1151 }
1152
1153 @Override
1154 protected void onPostExecute(Asset thumbAsset) {
1155 mReceiver.onAssetReceived(thumbAsset);
1156 }
1157 }
1158}