blob: 01c4001c0d3430b7422fb66b58311cb7c0cc6f91 [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;
111 private boolean mWasCustomPhotoWallpaperSet;
112 @WallpaperPosition
113 private int mCustomPhotoWallpaperPosition;
114
115 /**
116 * Progress dialogs for "refresh daily wallpaper" and "set wallpaper" operations.
117 */
118 private ProgressDialog mRefreshWallpaperProgressDialog;
119 private ProgressDialog mSetWallpaperProgressDialog;
120
121 /**
122 * Designates a test mode of operation -- in which certain UI features are disabled to allow for
123 * UI tests to run correctly.
124 */
125 private boolean mTestingMode;
126
127 /**
128 * UI for the "currently set wallpaper" BottomSheet.
129 */
130 private LinearLayout mBottomSheet;
131 private ImageView mCurrentWallpaperImage;
132 private TextView mCurrentWallpaperPresentationMode;
133 private TextView mCurrentWallpaperTitle;
134 private TextView mCurrentWallpaperSubtitle;
135 private Button mCurrentWallpaperExploreButton;
136 private Button mCurrentWallpaperSkipWallpaperButton;
137 private FrameLayout mFragmentContainer;
138 private FrameLayout mLoadingIndicatorContainer;
139 private LinearLayout mWallpaperPositionOptions;
140
Jon Miranda16ea1b12017-12-12 14:52:48 -0800141 /**
142 * Staged error dialog fragments that were unable to be shown when the activity didn't allow
143 * committing fragment transactions.
144 */
145 private SetWallpaperErrorDialogFragment mStagedSetWallpaperErrorDialogFragment;
146
147 /**
148 * A wallpaper pending set to the device--we retain a reference to this in order to facilitate
149 * retry or re-crop operations.
150 */
151 private WallpaperInfo mPendingSetWallpaperInfo;
152
153 private static int getTextColorIdForWallpaperPositionButton(boolean isSelected) {
154 return isSelected ? R.color.accent_color : R.color.material_grey500;
155 }
156
157 @Override
158 protected void onCreate(Bundle savedInstanceState) {
159 super.onCreate(savedInstanceState);
160
Jon Miranda16ea1b12017-12-12 14:52:48 -0800161 mLastSelectedCategoryTabIndex = -1;
162
163 Injector injector = InjectorProvider.getInjector();
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800164 mDelegate = new WallpaperPickerDelegate(this, this, injector);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800165 mUserEventLogger = injector.getUserEventLogger(this);
166 mNetworkStatusNotifier = injector.getNetworkStatusNotifier(this);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800167 mWallpaperPersister = injector.getWallpaperPersister(this);
168 mWasCustomPhotoWallpaperSet = false;
169
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800170 @WallpaperSupportLevel int wallpaperSupportLevel = mDelegate.getWallpaperSupportLevel();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800171 if (wallpaperSupportLevel != WallpaperDisabledFragment.SUPPORTED_CAN_SET) {
Chuck Liao8ec38e02020-02-26 20:59:32 +0800172 setContentView(R.layout.activity_top_level_picker);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800173
174 FragmentManager fm = getSupportFragmentManager();
175 WallpaperDisabledFragment wallpaperDisabledFragment =
176 WallpaperDisabledFragment.newInstance(wallpaperSupportLevel);
177 fm.beginTransaction()
178 .add(R.id.fragment_container, wallpaperDisabledFragment)
179 .commit();
180 return;
181 }
182
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800183 if (mDelegate.getFormFactor() == FormFactorChecker.FORM_FACTOR_MOBILE) {
Ching-Sung Li5f689972019-05-20 17:16:57 +0800184 initializeMobile(true /* shouldForceRefresh */);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800185 } else { // DESKTOP
186 initializeDesktop(savedInstanceState);
187 }
188 }
189
190 @Override
191 protected void onResume() {
192 super.onResume();
Hyunyoung Song8077c862019-06-18 01:14:24 -0400193 boolean provisioned = Settings.Global.getInt(getContentResolver(),
194 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
195
196 mUserEventLogger.logResumed(provisioned, true);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800197 // Show the staged 'load wallpaper' or 'set wallpaper' error dialog fragments if there is one
198 // that was unable to be shown earlier when this fragment's hosting activity didn't allow
199 // committing fragment transactions.
200 if (mStagedSetWallpaperErrorDialogFragment != null) {
201 mStagedSetWallpaperErrorDialogFragment.show(
202 getSupportFragmentManager(), TAG_SET_WALLPAPER_ERROR_DIALOG_FRAGMENT);
203 mStagedSetWallpaperErrorDialogFragment = null;
204 }
205 }
206
207 @Override
Santiago Etchebeherebd536c62019-04-09 15:25:51 -0300208 protected void onStop() {
209 mUserEventLogger.logStopped();
210 super.onStop();
211 }
212
213 @Override
Jon Miranda16ea1b12017-12-12 14:52:48 -0800214 protected void onDestroy() {
215 super.onDestroy();
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800216 mDelegate.cleanUp();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800217 if (mNetworkStatusListener != null) {
218 mNetworkStatusNotifier.unregisterListener(mNetworkStatusListener);
219 }
220
221 if (mRefreshWallpaperProgressDialog != null) {
222 mRefreshWallpaperProgressDialog.dismiss();
223 }
224 if (mSetWallpaperProgressDialog != null) {
225 mSetWallpaperProgressDialog.dismiss();
226 }
Jon Miranda16ea1b12017-12-12 14:52:48 -0800227 }
228
229 @Override
Chuck Liaob1f1a3a2020-02-17 19:46:14 +0800230 public void onBackPressed() {
231 CategoryFragment categoryFragment = getCategoryFragment();
232 if (categoryFragment != null && categoryFragment.popChildFragment()) {
233 return;
234 }
235 super.onBackPressed();
236 }
237
238 @Override
Jon Miranda16ea1b12017-12-12 14:52:48 -0800239 public void requestCustomPhotoPicker(PermissionChangedListener listener) {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800240 mDelegate.requestCustomPhotoPicker(listener);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800241 }
242
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800243 @Override
244 public void requestExternalStoragePermission(PermissionChangedListener listener) {
245 mDelegate.requestExternalStoragePermission(listener);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800246 }
247
248 /**
249 * Returns whether READ_EXTERNAL_STORAGE has been granted for the application.
250 */
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800251 public boolean isReadExternalStoragePermissionGranted() {
252 return mDelegate.isReadExternalStoragePermissionGranted();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800253 }
254
Ching-Sung Li5f689972019-05-20 17:16:57 +0800255 private void initializeMobile(boolean shouldForceRefresh) {
Chuck Liao8ec38e02020-02-26 20:59:32 +0800256 setContentView(R.layout.activity_top_level_picker);
Santiago Etchebehere35891ea2019-07-26 15:21:42 -0700257 getWindow().getDecorView().setSystemUiVisibility(
258 getWindow().getDecorView().getSystemUiVisibility()
259 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
260 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
Chuck Liao829d4d22020-05-07 17:00:10 +0800261 View fragmentContainer = findViewById(R.id.fragment_container);
262 fragmentContainer.setOnApplyWindowInsetsListener((view, windowInsets) -> {
Santiago Etchebehere35891ea2019-07-26 15:21:42 -0700263 view.setPadding(view.getPaddingLeft(), windowInsets.getSystemWindowInsetTop(),
Chuck Liaoe9d79812020-02-20 18:03:55 +0800264 view.getPaddingRight(), view.getPaddingBottom());
Santiago Etchebehere35891ea2019-07-26 15:21:42 -0700265 // Consume only the top inset (status bar), to let other content in the Activity consume
266 // the nav bar (ie, by using "fitSystemWindows")
267 if (BuildCompat.isAtLeastQ()) {
268 WindowInsets.Builder builder = new WindowInsets.Builder(windowInsets);
269 builder.setSystemWindowInsets(Insets.of(windowInsets.getSystemWindowInsetLeft(),
270 0, windowInsets.getStableInsetRight(),
271 windowInsets.getSystemWindowInsetBottom()));
272 return builder.build();
273 } else {
274 return windowInsets.replaceSystemWindowInsets(
275 windowInsets.getSystemWindowInsetLeft(),
276 0, windowInsets.getStableInsetRight(),
277 windowInsets.getSystemWindowInsetBottom());
278 }
279 });
Jon Miranda16ea1b12017-12-12 14:52:48 -0800280
Chuck Liao829d4d22020-05-07 17:00:10 +0800281 FrameLayout.LayoutParams layoutParams =
282 (FrameLayout.LayoutParams) fragmentContainer.getLayoutParams();
283 int bottomActionBarHeight = getResources()
284 .getDimensionPixelSize(R.dimen.bottom_navbar_height);
285 BottomActionBar bottomActionBar = findViewById(R.id.bottom_actionbar);
286 bottomActionBar.addVisibilityChangeListener(isVisible -> {
287 if (layoutParams != null) {
288 layoutParams.bottomMargin = isVisible ? bottomActionBarHeight : 0;
289 }
290 });
291
Jon Miranda16ea1b12017-12-12 14:52:48 -0800292 // Set toolbar as the action bar.
293 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
294 setSupportActionBar(toolbar);
295
296 FragmentManager fm = getSupportFragmentManager();
297 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
298
Jon Miranda16ea1b12017-12-12 14:52:48 -0800299 if (fragment == null) {
300 // App launch specific logic: log the "app launched" event and set up daily logging.
301 mUserEventLogger.logAppLaunched();
302 DailyLoggingAlarmScheduler.setAlarm(getApplicationContext());
303
Santiago Etchebehereaa35e6e2019-01-25 10:30:11 -0800304 CategoryFragment newFragment = CategoryFragment.newInstance(
305 getString(R.string.wallpaper_app_name));
Jon Miranda16ea1b12017-12-12 14:52:48 -0800306 fm.beginTransaction()
307 .add(R.id.fragment_container, newFragment)
308 .commit();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800309 }
310
Ching-Sung Li5f689972019-05-20 17:16:57 +0800311 mDelegate.initialize(shouldForceRefresh);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800312 }
313
314 private void initializeDesktop(Bundle savedInstanceState) {
315 setContentView(R.layout.activity_top_level_desktop);
316
317 mBottomSheet = (LinearLayout) findViewById(R.id.bottom_sheet);
318 mCurrentWallpaperImage = (ImageView) mBottomSheet.findViewById(R.id.current_wallpaper_image);
319 mCurrentWallpaperImage.getLayoutParams().width = getSingleWallpaperImageWidthPx();
320
321 mCurrentWallpaperPresentationMode =
322 (TextView) mBottomSheet.findViewById(R.id.current_wallpaper_presentation_mode);
323 mCurrentWallpaperTitle = (TextView) findViewById(R.id.current_wallpaper_title);
324 mCurrentWallpaperSubtitle = (TextView) findViewById(R.id.current_wallpaper_subtitle);
325 mCurrentWallpaperExploreButton = (Button) findViewById(
326 R.id.current_wallpaper_explore_button);
327 mCurrentWallpaperSkipWallpaperButton = (Button) findViewById(
328 R.id.current_wallpaper_skip_wallpaper_button);
329 mFragmentContainer = (FrameLayout) findViewById(R.id.fragment_container);
330 mLoadingIndicatorContainer = (FrameLayout) findViewById(R.id.loading_indicator_container);
331 mWallpaperPositionOptions = (LinearLayout) findViewById(
332 R.id.desktop_wallpaper_position_options);
333
334 final TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
335 tabLayout.addOnTabSelectedListener(new OnTabSelectedListener() {
336 @Override
337 public void onTabSelected(Tab tab) {
338 Category category = (Category) tab.getTag();
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800339 showCategoryDesktop(category.getCollectionId());
Jon Miranda16ea1b12017-12-12 14:52:48 -0800340 mLastSelectedCategoryTabIndex = tabLayout.getSelectedTabPosition();
341 }
342
343 @Override
344 public void onTabUnselected(Tab tab) {
345 }
346
347 @Override
348 public void onTabReselected(Tab tab) {
349 Category category = (Category) tab.getTag();
350 // If offline, "My photos" may be the only visible category. In this case we want to allow
351 // re-selection so user can still select a photo as wallpaper while offline.
352 if (!category.isEnumerable()) {
353 onTabSelected(tab);
354 }
355 }
356 });
357
358 FragmentManager fm = getSupportFragmentManager();
359 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
360
361 if (fragment == null) {
362 // App launch specific logic: log the "app launched" event and set up daily logging.
363 mUserEventLogger.logAppLaunched();
364 DailyLoggingAlarmScheduler.setAlarm(getApplicationContext());
365 }
366
367 mNetworkStatusListener = new NetworkStatusNotifier.Listener() {
368 @Override
369 public void onNetworkChanged(@NetworkStatus int networkStatus) {
370 initializeDesktopBasedOnNetwork(networkStatus, savedInstanceState);
371 }
372 };
373 // Upon registering a listener, the onNetworkChanged method is immediately called with the
374 // initial network status.
375 mNetworkStatusNotifier.registerListener(mNetworkStatusListener);
376 }
377
378 private void initializeDesktopBasedOnNetwork(@NetworkStatus int networkStatus,
379 Bundle savedInstanceState) {
380 if (networkStatus == NetworkStatusNotifier.NETWORK_CONNECTED) {
381 initializeDesktopOnline(savedInstanceState);
382 } else {
383 initializeDesktopOffline();
384 }
385 }
386
387 private void initializeDesktopOnline(Bundle savedInstanceState) {
388 FragmentManager fm = getSupportFragmentManager();
389 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
390
391 // Require a category refresh if this is the first load of the app or if the app is now
392 // returning online after having been offline.
393 boolean forceCategoryRefresh = fragment == null || fragment instanceof OfflineDesktopFragment;
394
395 if (fragment != null) {
396 fm.beginTransaction()
397 .remove(fragment)
398 .commit();
399 }
400
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800401 mLastSelectedCategoryTabIndex = savedInstanceState != null
Jon Miranda16ea1b12017-12-12 14:52:48 -0800402 ? savedInstanceState.getInt(KEY_SELECTED_CATEGORY_TAB) : -1;
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800403 mDelegate.populateCategories(forceCategoryRefresh);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800404
405 setDesktopLoading(true);
406 setUpBottomSheet();
407 refreshCurrentWallpapers(null /* refreshListener */);
408 }
409
410 private void initializeDesktopOffline() {
411 FragmentManager fm = getSupportFragmentManager();
412 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
413
414 if (fragment != null) {
415 fm.beginTransaction()
416 .remove(fragment)
417 .commit();
418 }
419 OfflineDesktopFragment newFragment = new OfflineDesktopFragment();
420 fm.beginTransaction()
421 .add(R.id.fragment_container, newFragment)
422 .commit();
423
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800424 // Reset the last selected category tab index to ensure the app doesn't try to reselect a
425 // tab for a category not yet repopulated.
Jon Miranda16ea1b12017-12-12 14:52:48 -0800426 mLastSelectedCategoryTabIndex = -1;
427
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800428 mDelegate.populateCategories(true /* forceCategoryRefresh */);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800429
430 setDesktopLoading(false);
431 setCurrentWallpapersExpanded(false);
432 }
433
434 /**
435 * Sets the status of the loading indicator overlay in desktop mode.
436 *
437 * @param loading Whether an indeterminate loading indicator is displayed in place of the main
438 * fragment.
439 */
440 private void setDesktopLoading(boolean loading) {
441 if (loading) {
442 mLoadingIndicatorContainer.setVisibility(View.VISIBLE);
443 mFragmentContainer.setVisibility(View.GONE);
444 } else {
445 mLoadingIndicatorContainer.setVisibility(View.GONE);
446 mFragmentContainer.setVisibility(View.VISIBLE);
447 }
448 }
449
450 /**
451 * Returns the width (in physical px) to use for the "currently set wallpaper" thumbnail.
452 */
453 private int getSingleWallpaperImageWidthPx() {
chihhangchuangc8442a72020-05-07 14:26:32 +0800454 final float screenAspectRatio =
455 ScreenSizeCalculator.getInstance().getScreenAspectRatio(this);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800456
457 int height = getResources().getDimensionPixelSize(
458 R.dimen.current_wallpaper_bottom_sheet_thumb_height);
chihhangchuangc8442a72020-05-07 14:26:32 +0800459 return (int) (height / screenAspectRatio);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800460 }
461
462 /**
463 * Enables and populates the "Currently set" wallpaper BottomSheet.
464 */
465 private void setUpBottomSheet() {
466 mBottomSheet.setVisibility(View.VISIBLE);
467
Jon Miranda16ea1b12017-12-12 14:52:48 -0800468 if (Flags.skipDailyWallpaperButtonEnabled) {
469 // Add "next" icon to the Next Wallpaper button
470 Drawable nextWallpaperButtonDrawable = getResources().getDrawable(
Santiago Etchebehered24506c2018-04-05 17:02:42 -0700471 R.drawable.ic_refresh_18px);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800472
473 // This Drawable's state is shared across the app, so make a copy of it before applying a
474 // color tint as not to affect other clients elsewhere in the app.
475 nextWallpaperButtonDrawable =
476 nextWallpaperButtonDrawable.getConstantState().newDrawable().mutate();
477 // Color the "compass" icon with the accent color.
478 nextWallpaperButtonDrawable.setColorFilter(
479 getResources().getColor(R.color.accent_color), Mode.SRC_IN);
480 ButtonDrawableSetterCompat.setDrawableToButtonStart(
481 mCurrentWallpaperSkipWallpaperButton, nextWallpaperButtonDrawable);
482 }
483
484 final BottomSheetBehavior<LinearLayout> bottomSheetBehavior =
485 BottomSheetBehavior.from(mBottomSheet);
486 bottomSheetBehavior.setBottomSheetCallback(new BottomSheetCallback() {
487 @Override
488 public void onStateChanged(@NonNull View view, int i) {
489 }
490
491 @Override
492 public void onSlide(@NonNull View view, float slideOffset) {
493 float alpha;
494 if (slideOffset >= 0) {
495 alpha = slideOffset;
496 } else {
497 alpha = 1f - slideOffset;
498 }
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800499 LinearLayout bottomSheetContents = findViewById(R.id.bottom_sheet_contents);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800500 bottomSheetContents.setAlpha(alpha);
501 }
502 });
503 }
504
505 /**
506 * Enables a test mode of operation -- in which certain UI features are disabled to allow for
507 * UI tests to run correctly. Works around issue in ProgressDialog currently where the dialog
508 * constantly keeps the UI thread alive and blocks a test forever.
509 */
510 void setTestingMode(boolean testingMode) {
511 mTestingMode = testingMode;
512 }
513
514 /**
515 * Obtains the {@link WallpaperInfo} object(s) representing the wallpaper(s) currently set to the
516 * device from the {@link CurrentWallpaperInfoFactory} and displays them in the BottomSheet.
517 */
518 @Override
519 public void refreshCurrentWallpapers(@Nullable RefreshListener refreshListener) {
520 final Injector injector = InjectorProvider.getInjector();
521 final Context appContext = getApplicationContext();
522
523 CurrentWallpaperInfoFactory factory = injector.getCurrentWallpaperFactory(this);
524 factory.createCurrentWallpaperInfos(new WallpaperInfoCallback() {
525 @Override
526 public void onWallpaperInfoCreated(
527 final WallpaperInfo homeWallpaper,
528 @Nullable final WallpaperInfo lockWallpaper,
529 @PresentationMode final int presentationMode) {
530
531 if (isDestroyed()) {
532 return;
533 }
534
535 // Fetch the home wallpaper's thumbnail asset asynchronously to work around expensive
536 // method call to WallpaperManager#getWallpaperFile made from the CurrentWallpaperInfoVN
537 // getAsset() method.
538 AssetReceiver assetReceiver = (Asset thumbAsset) -> {
539 if (isDestroyed()) {
540 return;
541 }
542
543 homeWallpaper.getThumbAsset(appContext).loadDrawableWithTransition(
544 TopLevelPickerActivity.this,
545 mCurrentWallpaperImage,
546 200 /* transitionDurationMillis */,
547 () -> {
548 if (refreshListener != null) {
549 refreshListener.onCurrentWallpaperRefreshed();
550 }
551 },
552 Color.TRANSPARENT);
553 };
554 new FetchThumbAssetTask(appContext, homeWallpaper, assetReceiver).executeOnExecutor(
555 AsyncTask.THREAD_POOL_EXECUTOR);
556
557 mCurrentWallpaperPresentationMode.setText(
558 AttributionFormatter.getHumanReadableWallpaperPresentationMode(
559 TopLevelPickerActivity.this, presentationMode));
560
561 List<String> attributions = homeWallpaper.getAttributions(appContext);
562 if (attributions.size() > 0 && attributions.get(0) != null) {
563 mCurrentWallpaperTitle.setText(attributions.get(0));
564 }
565
566 mCurrentWallpaperSubtitle.setText(
567 AttributionFormatter.formatWallpaperSubtitle(appContext, homeWallpaper));
568
569 final String actionUrl = homeWallpaper.getActionUrl(appContext);
570 if (actionUrl != null && !actionUrl.isEmpty()) {
571 Uri exploreUri = Uri.parse(actionUrl);
572
573 ExploreIntentChecker intentChecker = injector.getExploreIntentChecker(appContext);
574 intentChecker.fetchValidActionViewIntent(exploreUri, (@Nullable Intent exploreIntent) -> {
575 if (exploreIntent != null && !isDestroyed()) {
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700576 // Set the icon for the button
577 Drawable exploreButtonDrawable = getResources().getDrawable(
Santiago Etchebeheree0810d02018-05-10 17:39:40 -0700578 homeWallpaper.getActionIconRes(appContext));
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700579
580 // This Drawable's state is shared across the app, so make a copy of it
581 // before applying a color tint as not to affect other clients elsewhere
582 // in the app.
583 exploreButtonDrawable = exploreButtonDrawable.getConstantState()
584 .newDrawable().mutate();
585 // Color the "compass" icon with the accent color.
586 exploreButtonDrawable.setColorFilter(
587 getResources().getColor(R.color.accent_color), Mode.SRC_IN);
588
589 ButtonDrawableSetterCompat.setDrawableToButtonStart(
590 mCurrentWallpaperExploreButton, exploreButtonDrawable);
591 mCurrentWallpaperExploreButton.setText(getString(
Santiago Etchebeheree0810d02018-05-10 17:39:40 -0700592 homeWallpaper.getActionLabelRes(appContext)));
Jon Miranda16ea1b12017-12-12 14:52:48 -0800593 mCurrentWallpaperExploreButton.setVisibility(View.VISIBLE);
594 mCurrentWallpaperExploreButton.setOnClickListener(new OnClickListener() {
595 @Override
596 public void onClick(View v) {
Santiago Etchebeherece5613f2018-06-01 13:22:47 -0700597 mUserEventLogger.logActionClicked(
598 homeWallpaper.getCollectionId(appContext),
599 homeWallpaper.getActionLabelRes(appContext));
Jon Miranda16ea1b12017-12-12 14:52:48 -0800600 startActivity(exploreIntent);
601 }
602 });
603 }
604 });
605 } else {
606 mCurrentWallpaperExploreButton.setVisibility(View.GONE);
607 }
608
609 // Hide the wallpaper position options UI if the current home wallpaper is not from
610 // "my photos".
611 String homeCollectionId = homeWallpaper.getCollectionId(TopLevelPickerActivity.this);
612 if (mWallpaperPositionOptions != null
613 && homeCollectionId != null // May be null if app is being used for the first time.
614 && !homeCollectionId.equals(getString(R.string.image_wallpaper_collection_id))) {
615 mWallpaperPositionOptions.setVisibility(View.GONE);
616 }
617
618 boolean showSkipWallpaperButton = Flags.skipDailyWallpaperButtonEnabled
619 && presentationMode == WallpaperPreferences.PRESENTATION_MODE_ROTATING;
620 if (showSkipWallpaperButton) {
621 mCurrentWallpaperSkipWallpaperButton.setVisibility(View.VISIBLE);
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800622 mCurrentWallpaperSkipWallpaperButton.setOnClickListener(
623 v -> refreshDailyWallpaper());
Jon Miranda16ea1b12017-12-12 14:52:48 -0800624 } else {
625 mCurrentWallpaperSkipWallpaperButton.setVisibility(View.GONE);
626 }
627
628 if (refreshListener != null) {
629 refreshListener.onCurrentWallpaperRefreshed();
630 }
631 }
632 }, true /* forceRefresh */);
633 }
634
635 @Override
636 public void onSaveInstanceState(Bundle savedInstanceState) {
637 FormFactorChecker formFactorChecker = InjectorProvider.getInjector().getFormFactorChecker(this);
638 if (formFactorChecker.getFormFactor() == FormFactorChecker.FORM_FACTOR_DESKTOP) {
639 TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
640
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800641 // tabLayout is only present when the main IndividualPickerFragment is present (as
642 // opposed to
Jon Miranda16ea1b12017-12-12 14:52:48 -0800643 // the WallpaperDisabledFragment), so need this null check.
644 if (tabLayout != null) {
645 savedInstanceState.putInt(KEY_SELECTED_CATEGORY_TAB, tabLayout.getSelectedTabPosition());
646 }
647 }
648
649 super.onSaveInstanceState(savedInstanceState);
650 }
651
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800652 @Override
Santiago Etchebehere1ee76a22018-05-15 15:02:24 -0700653 @Nullable
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800654 public CategoryFragment getCategoryFragment() {
655 if (mDelegate.getFormFactor() != FormFactorChecker.FORM_FACTOR_MOBILE) {
Santiago Etchebehere1ee76a22018-05-15 15:02:24 -0700656 return null;
657 }
658 FragmentManager fm = getSupportFragmentManager();
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800659 return (CategoryFragment) fm.findFragmentById(R.id.fragment_container);
Santiago Etchebehere1ee76a22018-05-15 15:02:24 -0700660 }
661
Jon Miranda16ea1b12017-12-12 14:52:48 -0800662 /**
663 * Populates the category tabs on DESKTOP form factor.
664 *
665 * @param selectedTabPosition The position of the tab to show as selected, or -1 if no particular
666 * tab should be selected (in which case: the tab of the category for the currently set
667 * wallpaper will be selected if enumerable; if not, the first enumerable category's tab will
668 * be selected).
669 */
670 private void populateCategoryTabs(int selectedTabPosition) {
671 final TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
672 tabLayout.removeAllTabs();
673
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800674 String currentlySetCollectionId = mDelegate.getPreferences().getHomeWallpaperCollectionId();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800675
676 Tab tabToSelect = null;
677 Tab firstEnumerableCategoryTab = null;
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800678 for (int i = 0; i < mDelegate.getCategoryProvider().getSize(); i++) {
679 Category category = mDelegate.getCategoryProvider().getCategory(i);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800680
681 Tab tab = tabLayout.newTab();
682 tab.setText(category.getTitle());
683 tab.setTag(category);
684 tabLayout.addTab(tab, false /* setSelected */);
685
686 if (firstEnumerableCategoryTab == null && category.isEnumerable()) {
687 firstEnumerableCategoryTab = tab;
688 }
689
690 boolean shouldSelectTab = (i == selectedTabPosition)
691 || (selectedTabPosition == -1
692 && tabToSelect == null
693 && category.isEnumerable()
694 && currentlySetCollectionId != null
695 && currentlySetCollectionId.equals(category.getCollectionId()));
696
697 if (shouldSelectTab) {
698 tabToSelect = tab;
699 }
700 }
701
702 // If the above loop did not identify a specific tab to select, then just select the tab for
703 // the first enumerable category.
704 if (tabToSelect == null) {
705 tabToSelect = firstEnumerableCategoryTab;
706 }
707
708 // There may be no enumerable tabs (e.g., offline case), so we need to null-check again.
709 if (tabToSelect != null) {
710 tabToSelect.select();
711 }
712 }
713
714 /**
715 * Refreshes the current wallpaper in a daily wallpaper rotation.
716 */
717 private void refreshDailyWallpaper() {
718 // ProgressDialog endlessly updates the UI thread, keeping it from going idle which therefore
719 // causes Espresso to hang once the dialog is shown.
720 if (!mTestingMode) {
721 int themeResId;
722 if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
723 themeResId = R.style.ProgressDialogThemePreL;
724 } else {
725 themeResId = R.style.LightDialogTheme;
726 }
727 mRefreshWallpaperProgressDialog = new ProgressDialog(this, themeResId);
728 mRefreshWallpaperProgressDialog.setTitle(null);
729 mRefreshWallpaperProgressDialog.setMessage(
730 getResources().getString(R.string.refreshing_daily_wallpaper_dialog_message));
731 mRefreshWallpaperProgressDialog.setIndeterminate(true);
732 mRefreshWallpaperProgressDialog.show();
733 }
734
735 WallpaperRotationRefresher wallpaperRotationRefresher =
736 InjectorProvider.getInjector().getWallpaperRotationRefresher();
737 wallpaperRotationRefresher.refreshWallpaper(this, new Listener() {
738 @Override
739 public void onRefreshed() {
740 if (isDestroyed()) {
741 return;
742 }
743
744 if (mRefreshWallpaperProgressDialog != null) {
745 mRefreshWallpaperProgressDialog.dismiss();
746 }
747
748 refreshCurrentWallpapers(null /* refreshListener */);
749 }
750
751 @Override
752 public void onError() {
753 if (mRefreshWallpaperProgressDialog != null) {
754 mRefreshWallpaperProgressDialog.dismiss();
755 }
756
757 AlertDialog errorDialog = new AlertDialog.Builder(
758 TopLevelPickerActivity.this, R.style.LightDialogTheme)
759 .setMessage(R.string.refresh_daily_wallpaper_failed_message)
760 .setPositiveButton(android.R.string.ok, null /* onClickListener */)
761 .create();
762 errorDialog.show();
763 }
764 });
765 }
766
767 @Override
768 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
769 super.onActivityResult(requestCode, resultCode, data);
770
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800771 if (requestCode == WallpaperPickerDelegate.SHOW_CATEGORY_REQUEST_CODE
772 && resultCode == Activity.RESULT_OK) {
Santiago Etchebeheree5e05842019-02-13 16:58:07 -0800773 if (mDelegate.getFormFactor() == FormFactorChecker.FORM_FACTOR_DESKTOP) {
774 Uri imageUri = (data == null) ? null : data.getData();
775 if (imageUri != null) {
776 // User selected an image from the system picker, so launch the preview for that
777 // image.
778 ImageWallpaperInfo imageWallpaper = new ImageWallpaperInfo(imageUri);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800779 setCustomPhotoWallpaper(imageWallpaper);
780 return;
781 }
Jon Miranda16ea1b12017-12-12 14:52:48 -0800782 }
Santiago Etchebeheree5e05842019-02-13 16:58:07 -0800783 }
784 if (mDelegate.handleActivityResult(requestCode, resultCode, data)) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800785 finishActivityWithResultOk();
786 }
787 }
788
789 /**
790 * Shows the view-only preview activity for the given wallpaper.
791 */
792 public void showViewOnlyPreview(WallpaperInfo wallpaperInfo) {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800793 mDelegate.showViewOnlyPreview(wallpaperInfo);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800794 }
795
796 @Override
797 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
798 @NonNull int[] grantResults) {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800799 mDelegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800800 }
801
Jon Miranda16ea1b12017-12-12 14:52:48 -0800802 private void reselectLastTab() {
803 TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
804
805 // In the offline case, "My photos" could be the only category. Thus we need this check --
806 // to ensure that we don't try to select the "previously selected" category which was -1.
807 if (mLastSelectedCategoryTabIndex > -1) {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800808 Tab tabToSelect = tabLayout.getTabAt(
809 mLastSelectedCategoryTabIndex);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800810 if (((Category) tabToSelect.getTag()).isEnumerable()) {
811 tabToSelect.select();
812 }
813 }
814 }
815
Jon Miranda16ea1b12017-12-12 14:52:48 -0800816 private void showCategoryDesktop(String collectionId) {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800817 Category category = mDelegate.findCategoryForCollectionId(collectionId);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800818 if (category == null) {
819 return;
820 }
821
822 if (category.isEnumerable()) {
823 // Replace contained IndividualPickerFragment with a new instance for the given category.
824 final FragmentManager fm = getSupportFragmentManager();
825 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
826 if (fragment != null) {
827 fm.beginTransaction()
828 .remove(fragment)
829 .commit();
830 }
Ching-Sung Li31fbe5e2019-01-23 19:36:24 +0800831 Injector injector = InjectorProvider.getInjector();
832 IndividualPickerFragment newFragment = injector.getIndividualPickerFragment(
833 collectionId);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800834 fm.beginTransaction()
835 .add(R.id.fragment_container, newFragment)
836 .commit();
837 newFragment.setCurrentWallpaperBottomSheetPresenter(this);
838 newFragment.setWallpapersUiContainer(this);
839 } else {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800840 category.show(this, mDelegate.getPickerIntentFactory(),
841 WallpaperPickerDelegate.SHOW_CATEGORY_REQUEST_CODE);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800842
843 // Need to select the tab here in case we are coming back from a "My photos" in which case
844 // the tab would have been set to "My photos" while viewing a regular image category.
845 reselectLastTab();
846 }
847 }
848
849 private void finishActivityWithResultOk() {
850 overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
851 setResult(Activity.RESULT_OK);
852 finish();
853 }
854
Jon Miranda16ea1b12017-12-12 14:52:48 -0800855 @Override
856 public void setCurrentWallpapersExpanded(boolean expanded) {
857 final BottomSheetBehavior<LinearLayout> bottomSheetBehavior =
858 BottomSheetBehavior.from(mBottomSheet);
859 bottomSheetBehavior.setState(
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800860 expanded ? BottomSheetBehavior.STATE_EXPANDED
861 : BottomSheetBehavior.STATE_COLLAPSED);
862 }
863
864 @Override
865 public void doneFetchingCategories() {
866 populateCategoryTabs(mLastSelectedCategoryTabIndex);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800867 }
868
869 @Override
870 public void onWallpapersReady() {
871 setDesktopLoading(false);
872 setCurrentWallpapersExpanded(true);
873 }
874
875 @Override
Santiago Etchebeherefab49612019-01-15 12:22:42 -0800876 public MyPhotosStarter getMyPhotosStarter() {
877 return this;
878 }
879
880 @Override
Jon Miranda16ea1b12017-12-12 14:52:48 -0800881 public void onClickTryAgain(@Destination int unused) {
882 // Retry the set wallpaper operation with the default center-crop setting.
883 if (mPendingSetWallpaperInfo != null) {
884 setCustomPhotoWallpaper(mPendingSetWallpaperInfo);
885 }
886 }
887
888 /**
889 * Sets the provides wallpaper to the device with center-cropped and scaled to fit the device's
890 * default display.
891 */
892 private void setCustomPhotoWallpaper(final WallpaperInfo wallpaper) {
893 // Save this WallpaperInfo so we can retry this operation later if it fails.
894 mPendingSetWallpaperInfo = wallpaper;
895
896 showSettingWallpaperProgressDialog();
897
898 mWallpaperPersister.setIndividualWallpaperWithPosition(this, wallpaper,
899 WallpaperPersister.WALLPAPER_POSITION_CENTER_CROP, new SetWallpaperCallback() {
900 @Override
“Chuckffd832c2020-03-22 02:15:58 +0800901 public void onSuccess(WallpaperInfo wallpaperInfo) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800902 dismissSettingWallpaperProgressDialog();
903 refreshCurrentWallpapers(null /* refreshListener */);
904
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800905 mDelegate.getPreferences().setPendingWallpaperSetStatus(
Jon Miranda16ea1b12017-12-12 14:52:48 -0800906 WallpaperPreferences.WALLPAPER_SET_NOT_PENDING);
907 mUserEventLogger.logWallpaperSet(
908 wallpaper.getCollectionId(getApplicationContext()),
909 wallpaper.getWallpaperId());
910 mUserEventLogger.logWallpaperSetResult(UserEventLogger.WALLPAPER_SET_RESULT_SUCCESS);
911
912 // The user may have closed the activity before the set wallpaper operation completed.
913 if (isDestroyed()) {
914 return;
915 }
916
917 // Show the wallpaper crop option selector and bind click event handlers.
918 mWallpaperPositionOptions.setVisibility(View.VISIBLE);
919
920 mWasCustomPhotoWallpaperSet = true;
921 mCustomPhotoWallpaperPosition = WallpaperPersister.WALLPAPER_POSITION_CENTER_CROP;
922
923 initializeWallpaperPositionOptionClickHandlers(wallpaper);
924 }
925
926 @Override
927 public void onError(Throwable throwable) {
928 dismissSettingWallpaperProgressDialog();
929 showSetWallpaperErrorDialog();
930
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800931 mDelegate.getPreferences().setPendingWallpaperSetStatus(
Jon Miranda16ea1b12017-12-12 14:52:48 -0800932 WallpaperPreferences.WALLPAPER_SET_NOT_PENDING);
933 mUserEventLogger.logWallpaperSetResult(
934 UserEventLogger.WALLPAPER_SET_RESULT_FAILURE);
935 @WallpaperSetFailureReason int failureReason = ThrowableAnalyzer.isOOM(throwable)
936 ? UserEventLogger.WALLPAPER_SET_FAILURE_REASON_OOM
937 : UserEventLogger.WALLPAPER_SET_FAILURE_REASON_OTHER;
938 mUserEventLogger.logWallpaperSetFailureReason(failureReason);
939 Log.e(TAG, "Unable to set wallpaper from 'my photos'.");
940 }
941 });
942 }
943
944 /**
945 * Initializes the wallpaper position button click handlers to change the way the provided
946 * wallpaper is set to the device.
947 */
948 private void initializeWallpaperPositionOptionClickHandlers(final WallpaperInfo wallpaperInfo) {
949 Button centerCropOptionBtn = (Button) findViewById(R.id.wallpaper_position_option_center_crop);
950 Button stretchOptionBtn = (Button) findViewById(R.id.wallpaper_position_option_stretched);
951 Button centerOptionBtn = (Button) findViewById(R.id.wallpaper_position_option_center);
952
953 // The "center crop" wallpaper position button is selected by default.
954 setCenterCropWallpaperPositionButtonSelected(centerCropOptionBtn, true /* isSelected */);
955 centerCropOptionBtn.setOnClickListener(new OnClickListener() {
956 @Override
957 public void onClick(View view) {
958 mWallpaperPersister.setIndividualWallpaperWithPosition(TopLevelPickerActivity.this,
959 wallpaperInfo, WallpaperPersister.WALLPAPER_POSITION_CENTER_CROP,
960 new SetWallpaperCallback() {
961 @Override
“Chuckffd832c2020-03-22 02:15:58 +0800962 public void onSuccess(WallpaperInfo wallpaperInfo) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800963 // The user may have closed the activity before the set wallpaper operation
964 // completed.
965 if (isDestroyed()) {
966 return;
967 }
968
969 refreshCurrentWallpapers(null /* refreshListener */);
970
971 setCenterCropWallpaperPositionButtonSelected(
972 centerCropOptionBtn, true /* isSelected */);
973 setCenterWallpaperPositionButtonSelected(centerOptionBtn, false /* isSelected */);
974 setStretchWallpaperPositionButtonSelected(stretchOptionBtn, false /* isSelected */);
975
976 mCustomPhotoWallpaperPosition = WallpaperPersister.WALLPAPER_POSITION_CENTER_CROP;
977 }
978
979 @Override
980 public void onError(@Nullable Throwable throwable) {
981 // no-op
982 }
983 });
984 }
985 });
986
987 // "Stretch" is not selected by default.
988 setStretchWallpaperPositionButtonSelected(stretchOptionBtn, false /* isSelected */);
989 stretchOptionBtn.setOnClickListener(new OnClickListener() {
990 @Override
991 public void onClick(View view) {
992 mWallpaperPersister.setIndividualWallpaperWithPosition(TopLevelPickerActivity.this,
993 wallpaperInfo, WallpaperPersister.WALLPAPER_POSITION_STRETCH,
994 new SetWallpaperCallback() {
995 @Override
“Chuckffd832c2020-03-22 02:15:58 +0800996 public void onSuccess(WallpaperInfo wallpaperInfo) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800997 // The user may have closed the activity before the set wallpaper operation
998 // completed.
999 if (isDestroyed()) {
1000 return;
1001 }
1002
1003 refreshCurrentWallpapers(null /* refreshListener */);
1004
1005 setStretchWallpaperPositionButtonSelected(stretchOptionBtn, true /* isSelected */);
1006 setCenterCropWallpaperPositionButtonSelected(
1007 centerCropOptionBtn, false /* isSelected */);
1008 setCenterWallpaperPositionButtonSelected(centerOptionBtn, false /* isSelected */);
1009
1010 mCustomPhotoWallpaperPosition = WallpaperPersister.WALLPAPER_POSITION_STRETCH;
1011 }
1012
1013 @Override
1014 public void onError(@Nullable Throwable throwable) {
1015 // no-op
1016 }
1017 });
1018 }
1019 });
1020
1021 // "Center" is not selected by default.
1022 setCenterWallpaperPositionButtonSelected(centerOptionBtn, false /* isSelected */);
1023 centerOptionBtn.setOnClickListener(new OnClickListener() {
1024 @Override
1025 public void onClick(View view) {
1026 mWallpaperPersister.setIndividualWallpaperWithPosition(TopLevelPickerActivity.this,
1027 wallpaperInfo, WallpaperPersister.WALLPAPER_POSITION_CENTER,
1028 new SetWallpaperCallback() {
1029 @Override
“Chuckffd832c2020-03-22 02:15:58 +08001030 public void onSuccess(WallpaperInfo wallpaperInfo) {
Jon Miranda16ea1b12017-12-12 14:52:48 -08001031 // The user may have closed the activity before the set wallpaper operation
1032 // completed.
1033 if (isDestroyed()) {
1034 return;
1035 }
1036
1037 refreshCurrentWallpapers(null /* refreshListener */);
1038
1039 setCenterWallpaperPositionButtonSelected(centerOptionBtn, true /* isSelected */);
1040 setCenterCropWallpaperPositionButtonSelected(
1041 centerCropOptionBtn, false /* isSelected */);
1042 setStretchWallpaperPositionButtonSelected(stretchOptionBtn, false /* isSelected */);
1043
1044 mCustomPhotoWallpaperPosition = WallpaperPersister.WALLPAPER_POSITION_CENTER;
1045 }
1046
1047 @Override
1048 public void onError(@Nullable Throwable throwable) {
1049 // no-op
1050 }
1051 });
1052 }
1053 });
1054 }
1055
1056 private void setCenterWallpaperPositionButtonSelected(Button button, boolean isSelected) {
1057 int drawableId = isSelected ? R.drawable.center_blue : R.drawable.center_grey;
1058 ButtonDrawableSetterCompat.setDrawableToButtonStart(button, getDrawable(drawableId));
1059 button.setTextColor(getColor(getTextColorIdForWallpaperPositionButton(isSelected)));
1060 }
1061
1062 private void setCenterCropWallpaperPositionButtonSelected(Button button, boolean isSelected) {
1063 int drawableId = isSelected ? R.drawable.center_crop_blue : R.drawable.center_crop_grey;
1064 ButtonDrawableSetterCompat.setDrawableToButtonStart(button, getDrawable(drawableId));
1065 button.setTextColor(getColor(getTextColorIdForWallpaperPositionButton(isSelected)));
1066 }
1067
1068 private void setStretchWallpaperPositionButtonSelected(Button button, boolean isSelected) {
1069 int drawableId = isSelected ? R.drawable.stretch_blue : R.drawable.stretch_grey;
1070 ButtonDrawableSetterCompat.setDrawableToButtonStart(button, getDrawable(drawableId));
1071 button.setTextColor(getColor(getTextColorIdForWallpaperPositionButton(isSelected)));
1072 }
1073
1074 private void showSettingWallpaperProgressDialog() {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -08001075 // ProgressDialog endlessly updates the UI thread, keeping it from going idle which
1076 // therefore causes Espresso to hang once the dialog is shown.
Jon Miranda16ea1b12017-12-12 14:52:48 -08001077 if (!mTestingMode) {
1078 int themeResId;
1079 if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
1080 themeResId = R.style.ProgressDialogThemePreL;
1081 } else {
1082 themeResId = R.style.LightDialogTheme;
1083 }
1084 mSetWallpaperProgressDialog = new ProgressDialog(this, themeResId);
1085 mSetWallpaperProgressDialog.setTitle(null);
1086 mSetWallpaperProgressDialog.setMessage(
1087 getResources().getString(R.string.set_wallpaper_progress_message));
1088 mSetWallpaperProgressDialog.setIndeterminate(true);
1089 mSetWallpaperProgressDialog.show();
1090 }
1091 }
1092
1093 private void dismissSettingWallpaperProgressDialog() {
1094 if (mSetWallpaperProgressDialog != null) {
1095 mSetWallpaperProgressDialog.dismiss();
1096 }
1097 }
1098
1099 private void showSetWallpaperErrorDialog() {
1100 SetWallpaperErrorDialogFragment dialogFragment = SetWallpaperErrorDialogFragment.newInstance(
1101 R.string.set_wallpaper_error_message, WallpaperPersister.DEST_BOTH);
1102
1103 if (isSafeToCommitFragmentTransaction()) {
1104 dialogFragment.show(getSupportFragmentManager(), TAG_SET_WALLPAPER_ERROR_DIALOG_FRAGMENT);
1105 } else {
1106 mStagedSetWallpaperErrorDialogFragment = dialogFragment;
1107 }
1108 }
1109
chihhangchuang3efb6832020-04-17 02:06:25 +08001110 @Override
1111 public BottomActionBar getBottomActionBar() {
1112 return findViewById(R.id.bottom_actionbar);
1113 }
1114
Jon Miranda16ea1b12017-12-12 14:52:48 -08001115 private interface AssetReceiver {
1116 void onAssetReceived(Asset asset);
1117 }
1118
1119 /**
1120 * An AsyncTask for asynchronously fetching the thumbnail asset for a given WallpaperInfo.
1121 * Used to work around expensive method call to WallpaperManager#getWallpaperFile made from the
1122 * CurrentWallpaperInfoVN getAsset() method.
1123 */
1124 private static class FetchThumbAssetTask extends AsyncTask<Void, Void, Asset> {
1125 private Context mAppContext;
1126 private WallpaperInfo mWallpaperInfo;
1127 private AssetReceiver mReceiver;
1128
1129 public FetchThumbAssetTask(Context appContext, WallpaperInfo wallpaperInfo,
1130 AssetReceiver receiver) {
1131 mAppContext = appContext;
1132 mWallpaperInfo = wallpaperInfo;
1133 mReceiver = receiver;
1134 }
1135
1136 @Override
1137 protected Asset doInBackground(Void... params) {
1138 return mWallpaperInfo.getThumbAsset(mAppContext);
1139 }
1140
1141 @Override
1142 protected void onPostExecute(Asset thumbAsset) {
1143 mReceiver.onAssetReceived(thumbAsset);
1144 }
1145 }
1146}