blob: f58bec2f98fe6b66b218c21490932f7d90c8a243 [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;
Chuck Liaof646e052020-09-24 12:24:59 +080019import android.app.AlertDialog;
Jon Miranda16ea1b12017-12-12 14:52:48 -080020import android.app.ProgressDialog;
Jon Miranda16ea1b12017-12-12 14:52:48 -080021import android.content.Context;
22import android.content.Intent;
Jon Miranda16ea1b12017-12-12 14:52:48 -080023import android.graphics.Color;
Santiago Etchebehere35891ea2019-07-26 15:21:42 -070024import android.graphics.Insets;
Jon Miranda16ea1b12017-12-12 14:52:48 -080025import android.graphics.PorterDuff.Mode;
26import android.graphics.drawable.Drawable;
27import android.net.Uri;
28import android.os.AsyncTask;
29import android.os.Build.VERSION;
30import android.os.Build.VERSION_CODES;
31import android.os.Bundle;
Hyunyoung Song8077c862019-06-18 01:14:24 -040032import android.provider.Settings;
Jon Miranda16ea1b12017-12-12 14:52:48 -080033import android.util.Log;
34import android.view.View;
35import android.view.View.OnClickListener;
Santiago Etchebehere35891ea2019-07-26 15:21:42 -070036import android.view.WindowInsets;
Jon Miranda16ea1b12017-12-12 14:52:48 -080037import android.widget.Button;
38import android.widget.FrameLayout;
39import android.widget.ImageView;
40import android.widget.LinearLayout;
41import android.widget.TextView;
42
Santiago Etchebehere635e96f2018-12-04 18:31:34 -080043import androidx.annotation.NonNull;
44import androidx.annotation.Nullable;
Santiago Etchebehere635e96f2018-12-04 18:31:34 -080045import 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;
Kunhung Lic6701492021-01-28 17:35:56 +080076import com.android.wallpaper.picker.AppbarFragment.AppbarFragmentHost;
Santiago Etchebehere635e96f2018-12-04 18:31:34 -080077import com.android.wallpaper.picker.CategoryFragment.CategoryFragmentHost;
Jon Miranda16ea1b12017-12-12 14:52:48 -080078import com.android.wallpaper.picker.WallpaperDisabledFragment.WallpaperSupportLevel;
Jon Miranda16ea1b12017-12-12 14:52:48 -080079import com.android.wallpaper.picker.individual.IndividualPickerFragment;
80import com.android.wallpaper.util.ScreenSizeCalculator;
81import com.android.wallpaper.util.ThrowableAnalyzer;
chihhangchuang3efb6832020-04-17 02:06:25 +080082import com.android.wallpaper.widget.BottomActionBar;
83import com.android.wallpaper.widget.BottomActionBar.BottomActionBarHost;
Jon Miranda16ea1b12017-12-12 14:52:48 -080084
Sunny Goyal8600a3f2018-08-15 12:48:01 -070085import com.google.android.material.bottomsheet.BottomSheetBehavior;
86import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback;
87import com.google.android.material.tabs.TabLayout;
88import com.google.android.material.tabs.TabLayout.OnTabSelectedListener;
89import com.google.android.material.tabs.TabLayout.Tab;
90
Jon Miranda16ea1b12017-12-12 14:52:48 -080091import java.util.List;
92
93/**
94 * Activity allowing users to select a category of wallpapers to choose from.
95 */
96public class TopLevelPickerActivity extends BaseActivity implements WallpapersUiContainer,
97 CurrentWallpaperBottomSheetPresenter, SetWallpaperErrorDialogFragment.Listener,
Kunhung Lic6701492021-01-28 17:35:56 +080098 MyPhotosStarter, AppbarFragmentHost, CategoryFragmentHost, BottomActionBarHost {
Jon Miranda16ea1b12017-12-12 14:52:48 -080099
100 private static final String TAG_SET_WALLPAPER_ERROR_DIALOG_FRAGMENT =
101 "toplevel_set_wallpaper_error_dialog";
102
103 private static final String TAG = "TopLevelPicker";
104 private static final String KEY_SELECTED_CATEGORY_TAB = "selected_category_tab";
105
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800106 private WallpaperPickerDelegate mDelegate;
Jon Miranda16ea1b12017-12-12 14:52:48 -0800107 private int mLastSelectedCategoryTabIndex;
Jon Miranda16ea1b12017-12-12 14:52:48 -0800108 private UserEventLogger mUserEventLogger;
109 private NetworkStatusNotifier mNetworkStatusNotifier;
110 private NetworkStatusNotifier.Listener mNetworkStatusListener;
111 private WallpaperPersister mWallpaperPersister;
Kunhung Li166842e2020-05-13 19:19:06 +0800112 private WallpaperPreferences mWallpaperPreferences;
Jon Miranda16ea1b12017-12-12 14:52:48 -0800113 private boolean mWasCustomPhotoWallpaperSet;
114 @WallpaperPosition
115 private int mCustomPhotoWallpaperPosition;
116
117 /**
118 * Progress dialogs for "refresh daily wallpaper" and "set wallpaper" operations.
119 */
120 private ProgressDialog mRefreshWallpaperProgressDialog;
121 private ProgressDialog mSetWallpaperProgressDialog;
122
123 /**
124 * Designates a test mode of operation -- in which certain UI features are disabled to allow for
125 * UI tests to run correctly.
126 */
127 private boolean mTestingMode;
128
129 /**
130 * UI for the "currently set wallpaper" BottomSheet.
131 */
132 private LinearLayout mBottomSheet;
133 private ImageView mCurrentWallpaperImage;
134 private TextView mCurrentWallpaperPresentationMode;
135 private TextView mCurrentWallpaperTitle;
136 private TextView mCurrentWallpaperSubtitle;
137 private Button mCurrentWallpaperExploreButton;
138 private Button mCurrentWallpaperSkipWallpaperButton;
139 private FrameLayout mFragmentContainer;
140 private FrameLayout mLoadingIndicatorContainer;
141 private LinearLayout mWallpaperPositionOptions;
142
Jon Miranda16ea1b12017-12-12 14:52:48 -0800143 /**
144 * Staged error dialog fragments that were unable to be shown when the activity didn't allow
145 * committing fragment transactions.
146 */
147 private SetWallpaperErrorDialogFragment mStagedSetWallpaperErrorDialogFragment;
148
149 /**
150 * A wallpaper pending set to the device--we retain a reference to this in order to facilitate
151 * retry or re-crop operations.
152 */
153 private WallpaperInfo mPendingSetWallpaperInfo;
154
155 private static int getTextColorIdForWallpaperPositionButton(boolean isSelected) {
156 return isSelected ? R.color.accent_color : R.color.material_grey500;
157 }
158
159 @Override
160 protected void onCreate(Bundle savedInstanceState) {
161 super.onCreate(savedInstanceState);
162
Jon Miranda16ea1b12017-12-12 14:52:48 -0800163 mLastSelectedCategoryTabIndex = -1;
164
165 Injector injector = InjectorProvider.getInjector();
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800166 mDelegate = new WallpaperPickerDelegate(this, this, injector);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800167 mUserEventLogger = injector.getUserEventLogger(this);
168 mNetworkStatusNotifier = injector.getNetworkStatusNotifier(this);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800169 mWallpaperPersister = injector.getWallpaperPersister(this);
Kunhung Li83f72a82020-06-02 11:05:10 +0800170 mWallpaperPreferences = injector.getPreferences(this);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800171 mWasCustomPhotoWallpaperSet = false;
172
Chuck Liaoe2d35f52020-09-22 21:20:47 +0800173 mDelegate.getCategoryProvider().resetIfNeeded();
174
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800175 @WallpaperSupportLevel int wallpaperSupportLevel = mDelegate.getWallpaperSupportLevel();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800176 if (wallpaperSupportLevel != WallpaperDisabledFragment.SUPPORTED_CAN_SET) {
Chuck Liao8ec38e02020-02-26 20:59:32 +0800177 setContentView(R.layout.activity_top_level_picker);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800178
179 FragmentManager fm = getSupportFragmentManager();
180 WallpaperDisabledFragment wallpaperDisabledFragment =
181 WallpaperDisabledFragment.newInstance(wallpaperSupportLevel);
182 fm.beginTransaction()
183 .add(R.id.fragment_container, wallpaperDisabledFragment)
184 .commit();
185 return;
186 }
187
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800188 if (mDelegate.getFormFactor() == FormFactorChecker.FORM_FACTOR_MOBILE) {
Ching-Sung Li5f689972019-05-20 17:16:57 +0800189 initializeMobile(true /* shouldForceRefresh */);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800190 } else { // DESKTOP
191 initializeDesktop(savedInstanceState);
192 }
193 }
194
195 @Override
196 protected void onResume() {
197 super.onResume();
Hyunyoung Song8077c862019-06-18 01:14:24 -0400198 boolean provisioned = Settings.Global.getInt(getContentResolver(),
199 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
200
201 mUserEventLogger.logResumed(provisioned, true);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800202 // Show the staged 'load wallpaper' or 'set wallpaper' error dialog fragments if there is one
203 // that was unable to be shown earlier when this fragment's hosting activity didn't allow
204 // committing fragment transactions.
205 if (mStagedSetWallpaperErrorDialogFragment != null) {
206 mStagedSetWallpaperErrorDialogFragment.show(
207 getSupportFragmentManager(), TAG_SET_WALLPAPER_ERROR_DIALOG_FRAGMENT);
208 mStagedSetWallpaperErrorDialogFragment = null;
209 }
210 }
211
212 @Override
Santiago Etchebeherebd536c62019-04-09 15:25:51 -0300213 protected void onStop() {
214 mUserEventLogger.logStopped();
215 super.onStop();
216 }
217
218 @Override
Jon Miranda16ea1b12017-12-12 14:52:48 -0800219 protected void onDestroy() {
220 super.onDestroy();
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800221 mDelegate.cleanUp();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800222 if (mNetworkStatusListener != null) {
223 mNetworkStatusNotifier.unregisterListener(mNetworkStatusListener);
224 }
225
226 if (mRefreshWallpaperProgressDialog != null) {
227 mRefreshWallpaperProgressDialog.dismiss();
228 }
229 if (mSetWallpaperProgressDialog != null) {
230 mSetWallpaperProgressDialog.dismiss();
231 }
Jon Miranda16ea1b12017-12-12 14:52:48 -0800232 }
233
234 @Override
Chuck Liaob1f1a3a2020-02-17 19:46:14 +0800235 public void onBackPressed() {
Chuck Liaof24418e2020-05-10 02:29:44 +0800236 Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
237 if (fragment instanceof BottomActionBarFragment
238 && ((BottomActionBarFragment) fragment).onBackPressed()) {
239 return;
240 }
241
Chuck Liao8cbe49f2021-03-15 20:28:04 +0800242 if (fragment != null && fragment.getChildFragmentManager().popBackStackImmediate()) {
Chuck Liaob1f1a3a2020-02-17 19:46:14 +0800243 return;
244 }
245 super.onBackPressed();
246 }
247
248 @Override
Jon Miranda16ea1b12017-12-12 14:52:48 -0800249 public void requestCustomPhotoPicker(PermissionChangedListener listener) {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800250 mDelegate.requestCustomPhotoPicker(listener);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800251 }
252
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800253 @Override
254 public void requestExternalStoragePermission(PermissionChangedListener listener) {
255 mDelegate.requestExternalStoragePermission(listener);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800256 }
257
258 /**
259 * Returns whether READ_EXTERNAL_STORAGE has been granted for the application.
260 */
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800261 public boolean isReadExternalStoragePermissionGranted() {
262 return mDelegate.isReadExternalStoragePermissionGranted();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800263 }
264
Ching-Sung Li5f689972019-05-20 17:16:57 +0800265 private void initializeMobile(boolean shouldForceRefresh) {
Chuck Liao8ec38e02020-02-26 20:59:32 +0800266 setContentView(R.layout.activity_top_level_picker);
Santiago Etchebehere35891ea2019-07-26 15:21:42 -0700267 getWindow().getDecorView().setSystemUiVisibility(
268 getWindow().getDecorView().getSystemUiVisibility()
269 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
270 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
Chuck Liao829d4d22020-05-07 17:00:10 +0800271 View fragmentContainer = findViewById(R.id.fragment_container);
272 fragmentContainer.setOnApplyWindowInsetsListener((view, windowInsets) -> {
Santiago Etchebehere35891ea2019-07-26 15:21:42 -0700273 view.setPadding(view.getPaddingLeft(), windowInsets.getSystemWindowInsetTop(),
Chuck Liaoe9d79812020-02-20 18:03:55 +0800274 view.getPaddingRight(), view.getPaddingBottom());
Santiago Etchebehere35891ea2019-07-26 15:21:42 -0700275 // Consume only the top inset (status bar), to let other content in the Activity consume
276 // the nav bar (ie, by using "fitSystemWindows")
277 if (BuildCompat.isAtLeastQ()) {
278 WindowInsets.Builder builder = new WindowInsets.Builder(windowInsets);
279 builder.setSystemWindowInsets(Insets.of(windowInsets.getSystemWindowInsetLeft(),
280 0, windowInsets.getStableInsetRight(),
281 windowInsets.getSystemWindowInsetBottom()));
282 return builder.build();
283 } else {
284 return windowInsets.replaceSystemWindowInsets(
285 windowInsets.getSystemWindowInsetLeft(),
286 0, windowInsets.getStableInsetRight(),
287 windowInsets.getSystemWindowInsetBottom());
288 }
289 });
Jon Miranda16ea1b12017-12-12 14:52:48 -0800290
291 // Set toolbar as the action bar.
292 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
293 setSupportActionBar(toolbar);
294
295 FragmentManager fm = getSupportFragmentManager();
296 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
297
Jon Miranda16ea1b12017-12-12 14:52:48 -0800298 if (fragment == null) {
Wesley.CW Wang484cdf32020-09-25 19:18:51 +0800299 // App launch specific logic: log the "app launch source" event.
300 mUserEventLogger.logAppLaunched(getIntent());
Kunhung Li166842e2020-05-13 19:19:06 +0800301 mWallpaperPreferences.incrementAppLaunched();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800302 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 }
Jon Miranda16ea1b12017-12-12 14:52:48 -0800310 }
311
312 private void initializeDesktop(Bundle savedInstanceState) {
313 setContentView(R.layout.activity_top_level_desktop);
314
315 mBottomSheet = (LinearLayout) findViewById(R.id.bottom_sheet);
316 mCurrentWallpaperImage = (ImageView) mBottomSheet.findViewById(R.id.current_wallpaper_image);
317 mCurrentWallpaperImage.getLayoutParams().width = getSingleWallpaperImageWidthPx();
318
319 mCurrentWallpaperPresentationMode =
320 (TextView) mBottomSheet.findViewById(R.id.current_wallpaper_presentation_mode);
321 mCurrentWallpaperTitle = (TextView) findViewById(R.id.current_wallpaper_title);
322 mCurrentWallpaperSubtitle = (TextView) findViewById(R.id.current_wallpaper_subtitle);
323 mCurrentWallpaperExploreButton = (Button) findViewById(
324 R.id.current_wallpaper_explore_button);
325 mCurrentWallpaperSkipWallpaperButton = (Button) findViewById(
326 R.id.current_wallpaper_skip_wallpaper_button);
327 mFragmentContainer = (FrameLayout) findViewById(R.id.fragment_container);
328 mLoadingIndicatorContainer = (FrameLayout) findViewById(R.id.loading_indicator_container);
329 mWallpaperPositionOptions = (LinearLayout) findViewById(
330 R.id.desktop_wallpaper_position_options);
331
332 final TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
333 tabLayout.addOnTabSelectedListener(new OnTabSelectedListener() {
334 @Override
335 public void onTabSelected(Tab tab) {
336 Category category = (Category) tab.getTag();
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800337 showCategoryDesktop(category.getCollectionId());
Jon Miranda16ea1b12017-12-12 14:52:48 -0800338 mLastSelectedCategoryTabIndex = tabLayout.getSelectedTabPosition();
339 }
340
341 @Override
342 public void onTabUnselected(Tab tab) {
343 }
344
345 @Override
346 public void onTabReselected(Tab tab) {
347 Category category = (Category) tab.getTag();
348 // If offline, "My photos" may be the only visible category. In this case we want to allow
349 // re-selection so user can still select a photo as wallpaper while offline.
350 if (!category.isEnumerable()) {
351 onTabSelected(tab);
352 }
353 }
354 });
355
356 FragmentManager fm = getSupportFragmentManager();
357 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
358
359 if (fragment == null) {
Wesley.CW Wang484cdf32020-09-25 19:18:51 +0800360 // App launch specific logic: log the "app launch source" event.
361 mUserEventLogger.logAppLaunched(getIntent());
Kunhung Li166842e2020-05-13 19:19:06 +0800362 mWallpaperPreferences.incrementAppLaunched();
Jon Miranda16ea1b12017-12-12 14:52:48 -0800363 DailyLoggingAlarmScheduler.setAlarm(getApplicationContext());
364 }
365
366 mNetworkStatusListener = new NetworkStatusNotifier.Listener() {
367 @Override
368 public void onNetworkChanged(@NetworkStatus int networkStatus) {
369 initializeDesktopBasedOnNetwork(networkStatus, savedInstanceState);
370 }
371 };
372 // Upon registering a listener, the onNetworkChanged method is immediately called with the
373 // initial network status.
374 mNetworkStatusNotifier.registerListener(mNetworkStatusListener);
375 }
376
377 private void initializeDesktopBasedOnNetwork(@NetworkStatus int networkStatus,
378 Bundle savedInstanceState) {
379 if (networkStatus == NetworkStatusNotifier.NETWORK_CONNECTED) {
380 initializeDesktopOnline(savedInstanceState);
381 } else {
382 initializeDesktopOffline();
383 }
384 }
385
386 private void initializeDesktopOnline(Bundle savedInstanceState) {
387 FragmentManager fm = getSupportFragmentManager();
388 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
389
390 // Require a category refresh if this is the first load of the app or if the app is now
391 // returning online after having been offline.
392 boolean forceCategoryRefresh = fragment == null || fragment instanceof OfflineDesktopFragment;
393
394 if (fragment != null) {
395 fm.beginTransaction()
396 .remove(fragment)
397 .commit();
398 }
399
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800400 mLastSelectedCategoryTabIndex = savedInstanceState != null
Jon Miranda16ea1b12017-12-12 14:52:48 -0800401 ? savedInstanceState.getInt(KEY_SELECTED_CATEGORY_TAB) : -1;
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800402 mDelegate.populateCategories(forceCategoryRefresh);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800403
404 setDesktopLoading(true);
405 setUpBottomSheet();
406 refreshCurrentWallpapers(null /* refreshListener */);
407 }
408
409 private void initializeDesktopOffline() {
410 FragmentManager fm = getSupportFragmentManager();
411 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
412
413 if (fragment != null) {
414 fm.beginTransaction()
415 .remove(fragment)
416 .commit();
417 }
418 OfflineDesktopFragment newFragment = new OfflineDesktopFragment();
419 fm.beginTransaction()
420 .add(R.id.fragment_container, newFragment)
421 .commit();
422
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800423 // Reset the last selected category tab index to ensure the app doesn't try to reselect a
424 // tab for a category not yet repopulated.
Jon Miranda16ea1b12017-12-12 14:52:48 -0800425 mLastSelectedCategoryTabIndex = -1;
426
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800427 mDelegate.populateCategories(true /* forceCategoryRefresh */);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800428
429 setDesktopLoading(false);
430 setCurrentWallpapersExpanded(false);
431 }
432
433 /**
434 * Sets the status of the loading indicator overlay in desktop mode.
435 *
436 * @param loading Whether an indeterminate loading indicator is displayed in place of the main
437 * fragment.
438 */
439 private void setDesktopLoading(boolean loading) {
440 if (loading) {
441 mLoadingIndicatorContainer.setVisibility(View.VISIBLE);
442 mFragmentContainer.setVisibility(View.GONE);
443 } else {
444 mLoadingIndicatorContainer.setVisibility(View.GONE);
445 mFragmentContainer.setVisibility(View.VISIBLE);
446 }
447 }
448
449 /**
450 * Returns the width (in physical px) to use for the "currently set wallpaper" thumbnail.
451 */
452 private int getSingleWallpaperImageWidthPx() {
chihhangchuangc8442a72020-05-07 14:26:32 +0800453 final float screenAspectRatio =
454 ScreenSizeCalculator.getInstance().getScreenAspectRatio(this);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800455
456 int height = getResources().getDimensionPixelSize(
457 R.dimen.current_wallpaper_bottom_sheet_thumb_height);
chihhangchuangc8442a72020-05-07 14:26:32 +0800458 return (int) (height / screenAspectRatio);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800459 }
460
461 /**
462 * Enables and populates the "Currently set" wallpaper BottomSheet.
463 */
464 private void setUpBottomSheet() {
465 mBottomSheet.setVisibility(View.VISIBLE);
466
Jon Miranda16ea1b12017-12-12 14:52:48 -0800467 if (Flags.skipDailyWallpaperButtonEnabled) {
468 // Add "next" icon to the Next Wallpaper button
469 Drawable nextWallpaperButtonDrawable = getResources().getDrawable(
Santiago Etchebehered24506c2018-04-05 17:02:42 -0700470 R.drawable.ic_refresh_18px);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800471
472 // This Drawable's state is shared across the app, so make a copy of it before applying a
473 // color tint as not to affect other clients elsewhere in the app.
474 nextWallpaperButtonDrawable =
475 nextWallpaperButtonDrawable.getConstantState().newDrawable().mutate();
476 // Color the "compass" icon with the accent color.
477 nextWallpaperButtonDrawable.setColorFilter(
478 getResources().getColor(R.color.accent_color), Mode.SRC_IN);
479 ButtonDrawableSetterCompat.setDrawableToButtonStart(
480 mCurrentWallpaperSkipWallpaperButton, nextWallpaperButtonDrawable);
481 }
482
483 final BottomSheetBehavior<LinearLayout> bottomSheetBehavior =
484 BottomSheetBehavior.from(mBottomSheet);
485 bottomSheetBehavior.setBottomSheetCallback(new BottomSheetCallback() {
486 @Override
487 public void onStateChanged(@NonNull View view, int i) {
488 }
489
490 @Override
491 public void onSlide(@NonNull View view, float slideOffset) {
492 float alpha;
493 if (slideOffset >= 0) {
494 alpha = slideOffset;
495 } else {
496 alpha = 1f - slideOffset;
497 }
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800498 LinearLayout bottomSheetContents = findViewById(R.id.bottom_sheet_contents);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800499 bottomSheetContents.setAlpha(alpha);
500 }
501 });
502 }
503
504 /**
505 * Enables a test mode of operation -- in which certain UI features are disabled to allow for
506 * UI tests to run correctly. Works around issue in ProgressDialog currently where the dialog
507 * constantly keeps the UI thread alive and blocks a test forever.
508 */
509 void setTestingMode(boolean testingMode) {
510 mTestingMode = testingMode;
511 }
512
513 /**
514 * Obtains the {@link WallpaperInfo} object(s) representing the wallpaper(s) currently set to the
515 * device from the {@link CurrentWallpaperInfoFactory} and displays them in the BottomSheet.
516 */
517 @Override
518 public void refreshCurrentWallpapers(@Nullable RefreshListener refreshListener) {
519 final Injector injector = InjectorProvider.getInjector();
520 final Context appContext = getApplicationContext();
521
522 CurrentWallpaperInfoFactory factory = injector.getCurrentWallpaperFactory(this);
523 factory.createCurrentWallpaperInfos(new WallpaperInfoCallback() {
524 @Override
525 public void onWallpaperInfoCreated(
526 final WallpaperInfo homeWallpaper,
527 @Nullable final WallpaperInfo lockWallpaper,
528 @PresentationMode final int presentationMode) {
529
530 if (isDestroyed()) {
531 return;
532 }
533
534 // Fetch the home wallpaper's thumbnail asset asynchronously to work around expensive
535 // method call to WallpaperManager#getWallpaperFile made from the CurrentWallpaperInfoVN
536 // getAsset() method.
537 AssetReceiver assetReceiver = (Asset thumbAsset) -> {
538 if (isDestroyed()) {
539 return;
540 }
541
542 homeWallpaper.getThumbAsset(appContext).loadDrawableWithTransition(
543 TopLevelPickerActivity.this,
544 mCurrentWallpaperImage,
545 200 /* transitionDurationMillis */,
546 () -> {
547 if (refreshListener != null) {
548 refreshListener.onCurrentWallpaperRefreshed();
549 }
550 },
551 Color.TRANSPARENT);
552 };
553 new FetchThumbAssetTask(appContext, homeWallpaper, assetReceiver).executeOnExecutor(
554 AsyncTask.THREAD_POOL_EXECUTOR);
555
556 mCurrentWallpaperPresentationMode.setText(
557 AttributionFormatter.getHumanReadableWallpaperPresentationMode(
558 TopLevelPickerActivity.this, presentationMode));
559
560 List<String> attributions = homeWallpaper.getAttributions(appContext);
561 if (attributions.size() > 0 && attributions.get(0) != null) {
562 mCurrentWallpaperTitle.setText(attributions.get(0));
563 }
564
565 mCurrentWallpaperSubtitle.setText(
566 AttributionFormatter.formatWallpaperSubtitle(appContext, homeWallpaper));
567
568 final String actionUrl = homeWallpaper.getActionUrl(appContext);
569 if (actionUrl != null && !actionUrl.isEmpty()) {
570 Uri exploreUri = Uri.parse(actionUrl);
571
572 ExploreIntentChecker intentChecker = injector.getExploreIntentChecker(appContext);
573 intentChecker.fetchValidActionViewIntent(exploreUri, (@Nullable Intent exploreIntent) -> {
574 if (exploreIntent != null && !isDestroyed()) {
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700575 // Set the icon for the button
576 Drawable exploreButtonDrawable = getResources().getDrawable(
Santiago Etchebeheree0810d02018-05-10 17:39:40 -0700577 homeWallpaper.getActionIconRes(appContext));
Santiago Etchebehered1bd5092018-04-18 16:03:30 -0700578
579 // This Drawable's state is shared across the app, so make a copy of it
580 // before applying a color tint as not to affect other clients elsewhere
581 // in the app.
582 exploreButtonDrawable = exploreButtonDrawable.getConstantState()
583 .newDrawable().mutate();
584 // Color the "compass" icon with the accent color.
585 exploreButtonDrawable.setColorFilter(
586 getResources().getColor(R.color.accent_color), Mode.SRC_IN);
587
588 ButtonDrawableSetterCompat.setDrawableToButtonStart(
589 mCurrentWallpaperExploreButton, exploreButtonDrawable);
590 mCurrentWallpaperExploreButton.setText(getString(
Santiago Etchebeheree0810d02018-05-10 17:39:40 -0700591 homeWallpaper.getActionLabelRes(appContext)));
Jon Miranda16ea1b12017-12-12 14:52:48 -0800592 mCurrentWallpaperExploreButton.setVisibility(View.VISIBLE);
593 mCurrentWallpaperExploreButton.setOnClickListener(new OnClickListener() {
594 @Override
595 public void onClick(View v) {
Santiago Etchebeherece5613f2018-06-01 13:22:47 -0700596 mUserEventLogger.logActionClicked(
597 homeWallpaper.getCollectionId(appContext),
598 homeWallpaper.getActionLabelRes(appContext));
Jon Miranda16ea1b12017-12-12 14:52:48 -0800599 startActivity(exploreIntent);
600 }
601 });
602 }
603 });
604 } else {
605 mCurrentWallpaperExploreButton.setVisibility(View.GONE);
606 }
607
608 // Hide the wallpaper position options UI if the current home wallpaper is not from
609 // "my photos".
610 String homeCollectionId = homeWallpaper.getCollectionId(TopLevelPickerActivity.this);
611 if (mWallpaperPositionOptions != null
612 && homeCollectionId != null // May be null if app is being used for the first time.
613 && !homeCollectionId.equals(getString(R.string.image_wallpaper_collection_id))) {
614 mWallpaperPositionOptions.setVisibility(View.GONE);
615 }
616
617 boolean showSkipWallpaperButton = Flags.skipDailyWallpaperButtonEnabled
618 && presentationMode == WallpaperPreferences.PRESENTATION_MODE_ROTATING;
619 if (showSkipWallpaperButton) {
620 mCurrentWallpaperSkipWallpaperButton.setVisibility(View.VISIBLE);
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800621 mCurrentWallpaperSkipWallpaperButton.setOnClickListener(
622 v -> refreshDailyWallpaper());
Jon Miranda16ea1b12017-12-12 14:52:48 -0800623 } else {
624 mCurrentWallpaperSkipWallpaperButton.setVisibility(View.GONE);
625 }
626
627 if (refreshListener != null) {
628 refreshListener.onCurrentWallpaperRefreshed();
629 }
630 }
631 }, true /* forceRefresh */);
632 }
633
634 @Override
635 public void onSaveInstanceState(Bundle savedInstanceState) {
636 FormFactorChecker formFactorChecker = InjectorProvider.getInjector().getFormFactorChecker(this);
637 if (formFactorChecker.getFormFactor() == FormFactorChecker.FORM_FACTOR_DESKTOP) {
638 TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
639
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800640 // tabLayout is only present when the main IndividualPickerFragment is present (as
641 // opposed to
Jon Miranda16ea1b12017-12-12 14:52:48 -0800642 // the WallpaperDisabledFragment), so need this null check.
643 if (tabLayout != null) {
644 savedInstanceState.putInt(KEY_SELECTED_CATEGORY_TAB, tabLayout.getSelectedTabPosition());
645 }
646 }
647
648 super.onSaveInstanceState(savedInstanceState);
649 }
650
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800651 @Override
Santiago Etchebehere1ee76a22018-05-15 15:02:24 -0700652 @Nullable
Chuck Liao8cbe49f2021-03-15 20:28:04 +0800653 public CategorySelectorFragment getCategorySelectorFragment() {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800654 if (mDelegate.getFormFactor() != FormFactorChecker.FORM_FACTOR_MOBILE) {
Santiago Etchebehere1ee76a22018-05-15 15:02:24 -0700655 return null;
656 }
657 FragmentManager fm = getSupportFragmentManager();
Chuck Liao8cbe49f2021-03-15 20:28:04 +0800658 return ((CategoryFragment) fm.findFragmentById(
659 R.id.fragment_container)).getCategorySelectorFragment();
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 */
Ching-Sung Lief59efa2020-06-05 22:41:43 +0800792 public void showViewOnlyPreview(WallpaperInfo wallpaperInfo, boolean isViewAsHome) {
793 mDelegate.showViewOnlyPreview(wallpaperInfo, isViewAsHome);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800794 }
795
796 @Override
Chuck Liaoa63f1bf2020-06-11 01:35:42 +0800797 public void show(String collectionId) {
798 mDelegate.show(collectionId);
799 }
800
801 @Override
Chuck Liaoaee30432020-06-23 01:17:05 +0800802 public boolean isNavigationTabsContained() {
803 return false;
804 }
805
806 @Override
Chuck Liaof6b4b192020-08-07 02:31:32 +0800807 public void fetchCategories() {
808 mDelegate.initialize(!mDelegate.getCategoryProvider().isCategoriesFetched());
809 }
810
811 @Override
Chuck Liao3abf15b2020-12-17 22:33:02 +0800812 public void cleanUp() {
813 mDelegate.cleanUp();
814 }
815
816 @Override
Jon Miranda16ea1b12017-12-12 14:52:48 -0800817 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
818 @NonNull int[] grantResults) {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800819 mDelegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800820 }
821
Jon Miranda16ea1b12017-12-12 14:52:48 -0800822 private void reselectLastTab() {
823 TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
824
825 // In the offline case, "My photos" could be the only category. Thus we need this check --
826 // to ensure that we don't try to select the "previously selected" category which was -1.
827 if (mLastSelectedCategoryTabIndex > -1) {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800828 Tab tabToSelect = tabLayout.getTabAt(
829 mLastSelectedCategoryTabIndex);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800830 if (((Category) tabToSelect.getTag()).isEnumerable()) {
831 tabToSelect.select();
832 }
833 }
834 }
835
Jon Miranda16ea1b12017-12-12 14:52:48 -0800836 private void showCategoryDesktop(String collectionId) {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800837 Category category = mDelegate.findCategoryForCollectionId(collectionId);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800838 if (category == null) {
839 return;
840 }
841
842 if (category.isEnumerable()) {
843 // Replace contained IndividualPickerFragment with a new instance for the given category.
844 final FragmentManager fm = getSupportFragmentManager();
845 Fragment fragment = fm.findFragmentById(R.id.fragment_container);
846 if (fragment != null) {
847 fm.beginTransaction()
848 .remove(fragment)
849 .commit();
850 }
Ching-Sung Li31fbe5e2019-01-23 19:36:24 +0800851 Injector injector = InjectorProvider.getInjector();
852 IndividualPickerFragment newFragment = injector.getIndividualPickerFragment(
853 collectionId);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800854 fm.beginTransaction()
855 .add(R.id.fragment_container, newFragment)
856 .commit();
857 newFragment.setCurrentWallpaperBottomSheetPresenter(this);
858 newFragment.setWallpapersUiContainer(this);
859 } else {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800860 category.show(this, mDelegate.getPickerIntentFactory(),
861 WallpaperPickerDelegate.SHOW_CATEGORY_REQUEST_CODE);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800862
863 // Need to select the tab here in case we are coming back from a "My photos" in which case
864 // the tab would have been set to "My photos" while viewing a regular image category.
865 reselectLastTab();
866 }
867 }
868
869 private void finishActivityWithResultOk() {
870 overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
871 setResult(Activity.RESULT_OK);
872 finish();
873 }
874
Jon Miranda16ea1b12017-12-12 14:52:48 -0800875 @Override
876 public void setCurrentWallpapersExpanded(boolean expanded) {
877 final BottomSheetBehavior<LinearLayout> bottomSheetBehavior =
878 BottomSheetBehavior.from(mBottomSheet);
879 bottomSheetBehavior.setState(
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800880 expanded ? BottomSheetBehavior.STATE_EXPANDED
881 : BottomSheetBehavior.STATE_COLLAPSED);
882 }
883
884 @Override
885 public void doneFetchingCategories() {
886 populateCategoryTabs(mLastSelectedCategoryTabIndex);
Jon Miranda16ea1b12017-12-12 14:52:48 -0800887 }
888
889 @Override
890 public void onWallpapersReady() {
891 setDesktopLoading(false);
892 setCurrentWallpapersExpanded(true);
893 }
894
895 @Override
Santiago Etchebeherefab49612019-01-15 12:22:42 -0800896 public MyPhotosStarter getMyPhotosStarter() {
897 return this;
898 }
899
900 @Override
Jon Miranda16ea1b12017-12-12 14:52:48 -0800901 public void onClickTryAgain(@Destination int unused) {
902 // Retry the set wallpaper operation with the default center-crop setting.
903 if (mPendingSetWallpaperInfo != null) {
904 setCustomPhotoWallpaper(mPendingSetWallpaperInfo);
905 }
906 }
907
908 /**
909 * Sets the provides wallpaper to the device with center-cropped and scaled to fit the device's
910 * default display.
911 */
912 private void setCustomPhotoWallpaper(final WallpaperInfo wallpaper) {
913 // Save this WallpaperInfo so we can retry this operation later if it fails.
914 mPendingSetWallpaperInfo = wallpaper;
915
916 showSettingWallpaperProgressDialog();
917
918 mWallpaperPersister.setIndividualWallpaperWithPosition(this, wallpaper,
919 WallpaperPersister.WALLPAPER_POSITION_CENTER_CROP, new SetWallpaperCallback() {
920 @Override
“Chuckffd832c2020-03-22 02:15:58 +0800921 public void onSuccess(WallpaperInfo wallpaperInfo) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800922 dismissSettingWallpaperProgressDialog();
923 refreshCurrentWallpapers(null /* refreshListener */);
924
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800925 mDelegate.getPreferences().setPendingWallpaperSetStatus(
Jon Miranda16ea1b12017-12-12 14:52:48 -0800926 WallpaperPreferences.WALLPAPER_SET_NOT_PENDING);
927 mUserEventLogger.logWallpaperSet(
928 wallpaper.getCollectionId(getApplicationContext()),
929 wallpaper.getWallpaperId());
930 mUserEventLogger.logWallpaperSetResult(UserEventLogger.WALLPAPER_SET_RESULT_SUCCESS);
931
932 // The user may have closed the activity before the set wallpaper operation completed.
933 if (isDestroyed()) {
934 return;
935 }
936
937 // Show the wallpaper crop option selector and bind click event handlers.
938 mWallpaperPositionOptions.setVisibility(View.VISIBLE);
939
940 mWasCustomPhotoWallpaperSet = true;
941 mCustomPhotoWallpaperPosition = WallpaperPersister.WALLPAPER_POSITION_CENTER_CROP;
942
943 initializeWallpaperPositionOptionClickHandlers(wallpaper);
944 }
945
946 @Override
947 public void onError(Throwable throwable) {
948 dismissSettingWallpaperProgressDialog();
949 showSetWallpaperErrorDialog();
950
Santiago Etchebehere635e96f2018-12-04 18:31:34 -0800951 mDelegate.getPreferences().setPendingWallpaperSetStatus(
Jon Miranda16ea1b12017-12-12 14:52:48 -0800952 WallpaperPreferences.WALLPAPER_SET_NOT_PENDING);
953 mUserEventLogger.logWallpaperSetResult(
954 UserEventLogger.WALLPAPER_SET_RESULT_FAILURE);
955 @WallpaperSetFailureReason int failureReason = ThrowableAnalyzer.isOOM(throwable)
956 ? UserEventLogger.WALLPAPER_SET_FAILURE_REASON_OOM
957 : UserEventLogger.WALLPAPER_SET_FAILURE_REASON_OTHER;
958 mUserEventLogger.logWallpaperSetFailureReason(failureReason);
959 Log.e(TAG, "Unable to set wallpaper from 'my photos'.");
960 }
961 });
962 }
963
964 /**
965 * Initializes the wallpaper position button click handlers to change the way the provided
966 * wallpaper is set to the device.
967 */
968 private void initializeWallpaperPositionOptionClickHandlers(final WallpaperInfo wallpaperInfo) {
969 Button centerCropOptionBtn = (Button) findViewById(R.id.wallpaper_position_option_center_crop);
970 Button stretchOptionBtn = (Button) findViewById(R.id.wallpaper_position_option_stretched);
971 Button centerOptionBtn = (Button) findViewById(R.id.wallpaper_position_option_center);
972
973 // The "center crop" wallpaper position button is selected by default.
974 setCenterCropWallpaperPositionButtonSelected(centerCropOptionBtn, true /* isSelected */);
975 centerCropOptionBtn.setOnClickListener(new OnClickListener() {
976 @Override
977 public void onClick(View view) {
978 mWallpaperPersister.setIndividualWallpaperWithPosition(TopLevelPickerActivity.this,
979 wallpaperInfo, WallpaperPersister.WALLPAPER_POSITION_CENTER_CROP,
980 new SetWallpaperCallback() {
981 @Override
“Chuckffd832c2020-03-22 02:15:58 +0800982 public void onSuccess(WallpaperInfo wallpaperInfo) {
Jon Miranda16ea1b12017-12-12 14:52:48 -0800983 // The user may have closed the activity before the set wallpaper operation
984 // completed.
985 if (isDestroyed()) {
986 return;
987 }
988
989 refreshCurrentWallpapers(null /* refreshListener */);
990
991 setCenterCropWallpaperPositionButtonSelected(
992 centerCropOptionBtn, true /* isSelected */);
993 setCenterWallpaperPositionButtonSelected(centerOptionBtn, false /* isSelected */);
994 setStretchWallpaperPositionButtonSelected(stretchOptionBtn, false /* isSelected */);
995
996 mCustomPhotoWallpaperPosition = WallpaperPersister.WALLPAPER_POSITION_CENTER_CROP;
997 }
998
999 @Override
1000 public void onError(@Nullable Throwable throwable) {
1001 // no-op
1002 }
1003 });
1004 }
1005 });
1006
1007 // "Stretch" is not selected by default.
1008 setStretchWallpaperPositionButtonSelected(stretchOptionBtn, false /* isSelected */);
1009 stretchOptionBtn.setOnClickListener(new OnClickListener() {
1010 @Override
1011 public void onClick(View view) {
1012 mWallpaperPersister.setIndividualWallpaperWithPosition(TopLevelPickerActivity.this,
1013 wallpaperInfo, WallpaperPersister.WALLPAPER_POSITION_STRETCH,
1014 new SetWallpaperCallback() {
1015 @Override
“Chuckffd832c2020-03-22 02:15:58 +08001016 public void onSuccess(WallpaperInfo wallpaperInfo) {
Jon Miranda16ea1b12017-12-12 14:52:48 -08001017 // The user may have closed the activity before the set wallpaper operation
1018 // completed.
1019 if (isDestroyed()) {
1020 return;
1021 }
1022
1023 refreshCurrentWallpapers(null /* refreshListener */);
1024
1025 setStretchWallpaperPositionButtonSelected(stretchOptionBtn, true /* isSelected */);
1026 setCenterCropWallpaperPositionButtonSelected(
1027 centerCropOptionBtn, false /* isSelected */);
1028 setCenterWallpaperPositionButtonSelected(centerOptionBtn, false /* isSelected */);
1029
1030 mCustomPhotoWallpaperPosition = WallpaperPersister.WALLPAPER_POSITION_STRETCH;
1031 }
1032
1033 @Override
1034 public void onError(@Nullable Throwable throwable) {
1035 // no-op
1036 }
1037 });
1038 }
1039 });
1040
1041 // "Center" is not selected by default.
1042 setCenterWallpaperPositionButtonSelected(centerOptionBtn, false /* isSelected */);
1043 centerOptionBtn.setOnClickListener(new OnClickListener() {
1044 @Override
1045 public void onClick(View view) {
1046 mWallpaperPersister.setIndividualWallpaperWithPosition(TopLevelPickerActivity.this,
1047 wallpaperInfo, WallpaperPersister.WALLPAPER_POSITION_CENTER,
1048 new SetWallpaperCallback() {
1049 @Override
“Chuckffd832c2020-03-22 02:15:58 +08001050 public void onSuccess(WallpaperInfo wallpaperInfo) {
Jon Miranda16ea1b12017-12-12 14:52:48 -08001051 // The user may have closed the activity before the set wallpaper operation
1052 // completed.
1053 if (isDestroyed()) {
1054 return;
1055 }
1056
1057 refreshCurrentWallpapers(null /* refreshListener */);
1058
1059 setCenterWallpaperPositionButtonSelected(centerOptionBtn, true /* isSelected */);
1060 setCenterCropWallpaperPositionButtonSelected(
1061 centerCropOptionBtn, false /* isSelected */);
1062 setStretchWallpaperPositionButtonSelected(stretchOptionBtn, false /* isSelected */);
1063
1064 mCustomPhotoWallpaperPosition = WallpaperPersister.WALLPAPER_POSITION_CENTER;
1065 }
1066
1067 @Override
1068 public void onError(@Nullable Throwable throwable) {
1069 // no-op
1070 }
1071 });
1072 }
1073 });
1074 }
1075
1076 private void setCenterWallpaperPositionButtonSelected(Button button, boolean isSelected) {
1077 int drawableId = isSelected ? R.drawable.center_blue : R.drawable.center_grey;
1078 ButtonDrawableSetterCompat.setDrawableToButtonStart(button, getDrawable(drawableId));
1079 button.setTextColor(getColor(getTextColorIdForWallpaperPositionButton(isSelected)));
1080 }
1081
1082 private void setCenterCropWallpaperPositionButtonSelected(Button button, boolean isSelected) {
1083 int drawableId = isSelected ? R.drawable.center_crop_blue : R.drawable.center_crop_grey;
1084 ButtonDrawableSetterCompat.setDrawableToButtonStart(button, getDrawable(drawableId));
1085 button.setTextColor(getColor(getTextColorIdForWallpaperPositionButton(isSelected)));
1086 }
1087
1088 private void setStretchWallpaperPositionButtonSelected(Button button, boolean isSelected) {
1089 int drawableId = isSelected ? R.drawable.stretch_blue : R.drawable.stretch_grey;
1090 ButtonDrawableSetterCompat.setDrawableToButtonStart(button, getDrawable(drawableId));
1091 button.setTextColor(getColor(getTextColorIdForWallpaperPositionButton(isSelected)));
1092 }
1093
1094 private void showSettingWallpaperProgressDialog() {
Santiago Etchebehere635e96f2018-12-04 18:31:34 -08001095 // ProgressDialog endlessly updates the UI thread, keeping it from going idle which
1096 // therefore causes Espresso to hang once the dialog is shown.
Jon Miranda16ea1b12017-12-12 14:52:48 -08001097 if (!mTestingMode) {
1098 int themeResId;
1099 if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) {
1100 themeResId = R.style.ProgressDialogThemePreL;
1101 } else {
1102 themeResId = R.style.LightDialogTheme;
1103 }
1104 mSetWallpaperProgressDialog = new ProgressDialog(this, themeResId);
1105 mSetWallpaperProgressDialog.setTitle(null);
1106 mSetWallpaperProgressDialog.setMessage(
1107 getResources().getString(R.string.set_wallpaper_progress_message));
1108 mSetWallpaperProgressDialog.setIndeterminate(true);
1109 mSetWallpaperProgressDialog.show();
1110 }
1111 }
1112
1113 private void dismissSettingWallpaperProgressDialog() {
1114 if (mSetWallpaperProgressDialog != null) {
1115 mSetWallpaperProgressDialog.dismiss();
1116 }
1117 }
1118
1119 private void showSetWallpaperErrorDialog() {
1120 SetWallpaperErrorDialogFragment dialogFragment = SetWallpaperErrorDialogFragment.newInstance(
1121 R.string.set_wallpaper_error_message, WallpaperPersister.DEST_BOTH);
1122
1123 if (isSafeToCommitFragmentTransaction()) {
1124 dialogFragment.show(getSupportFragmentManager(), TAG_SET_WALLPAPER_ERROR_DIALOG_FRAGMENT);
1125 } else {
1126 mStagedSetWallpaperErrorDialogFragment = dialogFragment;
1127 }
1128 }
1129
chihhangchuang3efb6832020-04-17 02:06:25 +08001130 @Override
1131 public BottomActionBar getBottomActionBar() {
1132 return findViewById(R.id.bottom_actionbar);
1133 }
1134
Kunhung Lic6701492021-01-28 17:35:56 +08001135 @Override
1136 public void onUpArrowPressed() {
1137 onBackPressed();
1138 }
1139
1140 @Override
1141 public boolean isUpArrowSupported() {
1142 return true;
1143 }
1144
Jon Miranda16ea1b12017-12-12 14:52:48 -08001145 private interface AssetReceiver {
1146 void onAssetReceived(Asset asset);
1147 }
1148
1149 /**
1150 * An AsyncTask for asynchronously fetching the thumbnail asset for a given WallpaperInfo.
1151 * Used to work around expensive method call to WallpaperManager#getWallpaperFile made from the
1152 * CurrentWallpaperInfoVN getAsset() method.
1153 */
1154 private static class FetchThumbAssetTask extends AsyncTask<Void, Void, Asset> {
1155 private Context mAppContext;
1156 private WallpaperInfo mWallpaperInfo;
1157 private AssetReceiver mReceiver;
1158
1159 public FetchThumbAssetTask(Context appContext, WallpaperInfo wallpaperInfo,
1160 AssetReceiver receiver) {
1161 mAppContext = appContext;
1162 mWallpaperInfo = wallpaperInfo;
1163 mReceiver = receiver;
1164 }
1165
1166 @Override
1167 protected Asset doInBackground(Void... params) {
1168 return mWallpaperInfo.getThumbAsset(mAppContext);
1169 }
1170
1171 @Override
1172 protected void onPostExecute(Asset thumbAsset) {
1173 mReceiver.onAssetReceived(thumbAsset);
1174 }
1175 }
1176}