1 /*
2  * Copyright (C) 2019 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  */
16 package com.android.launcher3.hybridhotseat;
17 
18 import static com.android.launcher3.LauncherAnimUtils.SCALE_PROPERTY;
19 import static com.android.launcher3.LauncherState.NORMAL;
20 import static com.android.launcher3.anim.AnimatorListeners.forSuccessCallback;
21 import static com.android.launcher3.hybridhotseat.HotseatEduController.getSettingsIntent;
22 import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_HOTSEAT_PREDICTION_PINNED;
23 import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_HOTSEAT_RANKED;
24 import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
25 
26 import android.animation.Animator;
27 import android.animation.AnimatorSet;
28 import android.animation.ObjectAnimator;
29 import android.content.ComponentName;
30 import android.view.HapticFeedbackConstants;
31 import android.view.View;
32 import android.view.ViewGroup;
33 
34 import androidx.annotation.NonNull;
35 import androidx.annotation.Nullable;
36 
37 import com.android.launcher3.DeviceProfile;
38 import com.android.launcher3.DragSource;
39 import com.android.launcher3.DropTarget;
40 import com.android.launcher3.Hotseat;
41 import com.android.launcher3.LauncherSettings;
42 import com.android.launcher3.R;
43 import com.android.launcher3.anim.AnimationSuccessListener;
44 import com.android.launcher3.config.FeatureFlags;
45 import com.android.launcher3.dragndrop.DragController;
46 import com.android.launcher3.dragndrop.DragOptions;
47 import com.android.launcher3.graphics.DragPreviewProvider;
48 import com.android.launcher3.logger.LauncherAtom.ContainerInfo;
49 import com.android.launcher3.logger.LauncherAtom.PredictedHotseatContainer;
50 import com.android.launcher3.logging.InstanceId;
51 import com.android.launcher3.model.BgDataModel.FixedContainerItems;
52 import com.android.launcher3.model.data.ItemInfo;
53 import com.android.launcher3.model.data.WorkspaceItemInfo;
54 import com.android.launcher3.popup.SystemShortcut;
55 import com.android.launcher3.touch.ItemLongClickListener;
56 import com.android.launcher3.uioverrides.PredictedAppIcon;
57 import com.android.launcher3.uioverrides.QuickstepLauncher;
58 import com.android.launcher3.util.ItemInfoMatcher;
59 import com.android.launcher3.util.OnboardingPrefs;
60 import com.android.launcher3.views.Snackbar;
61 
62 import java.util.ArrayList;
63 import java.util.Collections;
64 import java.util.List;
65 import java.util.stream.Collectors;
66 
67 /**
68  * Provides prediction ability for the hotseat. Fills gaps in hotseat with predicted items, allows
69  * pinning of predicted apps and manages replacement of predicted apps with user drag.
70  */
71 public class HotseatPredictionController implements DragController.DragListener,
72         SystemShortcut.Factory<QuickstepLauncher>, DeviceProfile.OnDeviceProfileChangeListener,
73         DragSource, ViewGroup.OnHierarchyChangeListener {
74 
75     private static final int FLAG_UPDATE_PAUSED = 1 << 0;
76     private static final int FLAG_DRAG_IN_PROGRESS = 1 << 1;
77     private static final int FLAG_FILL_IN_PROGRESS = 1 << 2;
78     private static final int FLAG_REMOVING_PREDICTED_ICON = 1 << 3;
79 
80     private int mHotSeatItemsCount;
81 
82     private QuickstepLauncher mLauncher;
83     private final Hotseat mHotseat;
84     private final Runnable mUpdateFillIfNotLoading = this::updateFillIfNotLoading;
85 
86     private List<ItemInfo> mPredictedItems = Collections.emptyList();
87 
88     private AnimatorSet mIconRemoveAnimators;
89     private int mPauseFlags = 0;
90 
91     private List<PredictedAppIcon.PredictedIconOutlineDrawing> mOutlineDrawings = new ArrayList<>();
92 
93     private final View.OnLongClickListener mPredictionLongClickListener = v -> {
94         if (!ItemLongClickListener.canStartDrag(mLauncher)) return false;
95         if (mLauncher.getWorkspace().isSwitchingState()) return false;
96         if (!mLauncher.getOnboardingPrefs().getBoolean(
97                 OnboardingPrefs.HOTSEAT_LONGPRESS_TIP_SEEN)) {
98             Snackbar.show(mLauncher, R.string.hotseat_tip_gaps_filled,
99                     R.string.hotseat_prediction_settings, null,
100                     () -> mLauncher.startActivity(getSettingsIntent()));
101             mLauncher.getOnboardingPrefs().markChecked(OnboardingPrefs.HOTSEAT_LONGPRESS_TIP_SEEN);
102             mLauncher.getDragLayer().performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
103             return true;
104         }
105 
106         // Start the drag
107         // Use a new itemInfo so that the original predicted item is stable
108         WorkspaceItemInfo dragItem = new WorkspaceItemInfo((WorkspaceItemInfo) v.getTag());
109         v.setVisibility(View.INVISIBLE);
110         mLauncher.getWorkspace().beginDragShared(
111                 v, null, this, dragItem, new DragPreviewProvider(v),
112                 mLauncher.getDefaultWorkspaceDragOptions());
113         return true;
114     };
115 
HotseatPredictionController(QuickstepLauncher launcher)116     public HotseatPredictionController(QuickstepLauncher launcher) {
117         mLauncher = launcher;
118         mHotseat = launcher.getHotseat();
119         mHotSeatItemsCount = mLauncher.getDeviceProfile().numShownHotseatIcons;
120         mLauncher.getDragController().addDragListener(this);
121 
122         launcher.addOnDeviceProfileChangeListener(this);
123         mHotseat.getShortcutsAndWidgets().setOnHierarchyChangeListener(this);
124     }
125 
126     @Override
onChildViewAdded(View parent, View child)127     public void onChildViewAdded(View parent, View child) {
128         onHotseatHierarchyChanged();
129     }
130 
131     @Override
onChildViewRemoved(View parent, View child)132     public void onChildViewRemoved(View parent, View child) {
133         onHotseatHierarchyChanged();
134     }
135 
onHotseatHierarchyChanged()136     private void onHotseatHierarchyChanged() {
137         if (mPauseFlags == 0 && !mLauncher.isWorkspaceLoading()) {
138             // Post update after a single frame to avoid layout within layout
139             MAIN_EXECUTOR.getHandler().removeCallbacks(mUpdateFillIfNotLoading);
140             MAIN_EXECUTOR.getHandler().post(mUpdateFillIfNotLoading);
141         }
142     }
143 
updateFillIfNotLoading()144     private void updateFillIfNotLoading() {
145         if (mPauseFlags == 0 && !mLauncher.isWorkspaceLoading()) {
146             fillGapsWithPrediction(true);
147         }
148     }
149 
150     /**
151      * Shows appropriate hotseat education based on prediction enabled and migration states.
152      */
showEdu()153     public void showEdu() {
154         mLauncher.getStateManager().goToState(NORMAL, true, forSuccessCallback(() -> {
155             HotseatEduController eduController = new HotseatEduController(mLauncher);
156             eduController.setPredictedApps(mPredictedItems.stream()
157                     .map(i -> (WorkspaceItemInfo) i)
158                     .collect(Collectors.toList()));
159             eduController.showEdu();
160         }));
161     }
162 
163     /**
164      * Returns if hotseat client has predictions
165      */
hasPredictions()166     public boolean hasPredictions() {
167         return !mPredictedItems.isEmpty();
168     }
169 
fillGapsWithPrediction()170     private void fillGapsWithPrediction() {
171         fillGapsWithPrediction(false);
172     }
173 
fillGapsWithPrediction(boolean animate)174     private void fillGapsWithPrediction(boolean animate) {
175         if (mPauseFlags != 0) {
176             return;
177         }
178 
179         int predictionIndex = 0;
180         int numViewsAnimated = 0;
181         ArrayList<WorkspaceItemInfo> newItems = new ArrayList<>();
182         // make sure predicted icon removal and filling predictions don't step on each other
183         if (mIconRemoveAnimators != null && mIconRemoveAnimators.isRunning()) {
184             mIconRemoveAnimators.addListener(new AnimationSuccessListener() {
185                 @Override
186                 public void onAnimationSuccess(Animator animator) {
187                     fillGapsWithPrediction(animate);
188                     mIconRemoveAnimators.removeListener(this);
189                 }
190             });
191             return;
192         }
193 
194         mPauseFlags |= FLAG_FILL_IN_PROGRESS;
195         for (int rank = 0; rank < mHotSeatItemsCount; rank++) {
196             View child = mHotseat.getChildAt(
197                     mHotseat.getCellXFromOrder(rank),
198                     mHotseat.getCellYFromOrder(rank));
199 
200             if (child != null && !isPredictedIcon(child)) {
201                 continue;
202             }
203             if (mPredictedItems.size() <= predictionIndex) {
204                 // Remove predicted apps from the past
205                 if (isPredictedIcon(child)) {
206                     mHotseat.removeView(child);
207                 }
208                 continue;
209             }
210             WorkspaceItemInfo predictedItem =
211                     (WorkspaceItemInfo) mPredictedItems.get(predictionIndex++);
212             if (isPredictedIcon(child) && child.isEnabled()) {
213                 PredictedAppIcon icon = (PredictedAppIcon) child;
214                 boolean animateIconChange = icon.shouldAnimateIconChange(predictedItem);
215                 icon.applyFromWorkspaceItem(predictedItem, animateIconChange, numViewsAnimated);
216                 if (animateIconChange) {
217                     numViewsAnimated++;
218                 }
219                 icon.finishBinding(mPredictionLongClickListener);
220             } else {
221                 newItems.add(predictedItem);
222             }
223             preparePredictionInfo(predictedItem, rank);
224         }
225         bindItems(newItems, animate);
226 
227         mPauseFlags &= ~FLAG_FILL_IN_PROGRESS;
228     }
229 
bindItems(List<WorkspaceItemInfo> itemsToAdd, boolean animate)230     private void bindItems(List<WorkspaceItemInfo> itemsToAdd, boolean animate) {
231         AnimatorSet animationSet = new AnimatorSet();
232         for (WorkspaceItemInfo item : itemsToAdd) {
233             PredictedAppIcon icon = PredictedAppIcon.createIcon(mHotseat, item);
234             mLauncher.getWorkspace().addInScreenFromBind(icon, item);
235             icon.finishBinding(mPredictionLongClickListener);
236             if (animate) {
237                 animationSet.play(ObjectAnimator.ofFloat(icon, SCALE_PROPERTY, 0.2f, 1));
238             }
239         }
240         if (animate) {
241             animationSet.addListener(
242                     forSuccessCallback(this::removeOutlineDrawings));
243             animationSet.start();
244         } else {
245             removeOutlineDrawings();
246         }
247     }
248 
removeOutlineDrawings()249     private void removeOutlineDrawings() {
250         if (mOutlineDrawings.isEmpty()) return;
251         for (PredictedAppIcon.PredictedIconOutlineDrawing outlineDrawing : mOutlineDrawings) {
252             mHotseat.removeDelegatedCellDrawing(outlineDrawing);
253         }
254         mHotseat.invalidate();
255         mOutlineDrawings.clear();
256     }
257 
258 
259     /**
260      * Unregisters callbacks and frees resources
261      */
destroy()262     public void destroy() {
263         mLauncher.removeOnDeviceProfileChangeListener(this);
264     }
265 
266     /**
267      * start and pauses predicted apps update on the hotseat
268      */
setPauseUIUpdate(boolean paused)269     public void setPauseUIUpdate(boolean paused) {
270         mPauseFlags = paused
271                 ? (mPauseFlags | FLAG_UPDATE_PAUSED)
272                 : (mPauseFlags & ~FLAG_UPDATE_PAUSED);
273         if (!paused) {
274             fillGapsWithPrediction();
275         }
276     }
277 
278     /**
279      * Sets or updates the predicted items
280      */
setPredictedItems(FixedContainerItems items)281     public void setPredictedItems(FixedContainerItems items) {
282         boolean shouldIgnoreVisibility = FeatureFlags.ENABLE_APP_PREDICTIONS_WHILE_VISIBLE.get()
283                 || mLauncher.isWorkspaceLoading()
284                 || mPredictedItems.equals(items.items)
285                 || mHotseat.getShortcutsAndWidgets().getChildCount() < mHotSeatItemsCount;
286         if (!shouldIgnoreVisibility
287                 && mHotseat.isShown()
288                 && mHotseat.getWindowVisibility() == View.VISIBLE) {
289             mHotseat.setOnVisibilityAggregatedCallback((isVisible) -> {
290                 if (isVisible) {
291                     return;
292                 }
293                 mHotseat.setOnVisibilityAggregatedCallback(null);
294 
295                 applyPredictedItems(items);
296             });
297         } else {
298             mHotseat.setOnVisibilityAggregatedCallback(null);
299 
300             applyPredictedItems(items);
301         }
302     }
303 
304     /**
305      * Sets or updates the predicted items only once the hotseat becomes hidden to the user
306      */
applyPredictedItems(FixedContainerItems items)307     private void applyPredictedItems(FixedContainerItems items) {
308         mPredictedItems = items.items;
309         if (mPredictedItems.isEmpty()) {
310             HotseatRestoreHelper.restoreBackup(mLauncher);
311         }
312         fillGapsWithPrediction();
313     }
314 
315     /**
316      * Pins a predicted app icon into place.
317      */
pinPrediction(ItemInfo info)318     public void pinPrediction(ItemInfo info) {
319         PredictedAppIcon icon = (PredictedAppIcon) mHotseat.getChildAt(
320                 mHotseat.getCellXFromOrder(info.rank),
321                 mHotseat.getCellYFromOrder(info.rank));
322         if (icon == null) {
323             return;
324         }
325         WorkspaceItemInfo workspaceItemInfo = new WorkspaceItemInfo((WorkspaceItemInfo) info);
326         mLauncher.getModelWriter().addItemToDatabase(workspaceItemInfo,
327                 LauncherSettings.Favorites.CONTAINER_HOTSEAT, workspaceItemInfo.screenId,
328                 workspaceItemInfo.cellX, workspaceItemInfo.cellY);
329         ObjectAnimator.ofFloat(icon, SCALE_PROPERTY, 1, 0.8f, 1).start();
330         icon.pin(workspaceItemInfo);
331         mLauncher.getStatsLogManager().logger()
332                 .withItemInfo(workspaceItemInfo)
333                 .log(LAUNCHER_HOTSEAT_PREDICTION_PINNED);
334     }
335 
getPredictedIcons()336     private List<PredictedAppIcon> getPredictedIcons() {
337         List<PredictedAppIcon> icons = new ArrayList<>();
338         ViewGroup vg = mHotseat.getShortcutsAndWidgets();
339         for (int i = 0; i < vg.getChildCount(); i++) {
340             View child = vg.getChildAt(i);
341             if (isPredictedIcon(child)) {
342                 icons.add((PredictedAppIcon) child);
343             }
344         }
345         return icons;
346     }
347 
removePredictedApps(List<PredictedAppIcon.PredictedIconOutlineDrawing> outlines, DropTarget.DragObject dragObject)348     private void removePredictedApps(List<PredictedAppIcon.PredictedIconOutlineDrawing> outlines,
349             DropTarget.DragObject dragObject) {
350         if (mIconRemoveAnimators != null) {
351             mIconRemoveAnimators.end();
352         }
353         mIconRemoveAnimators = new AnimatorSet();
354         removeOutlineDrawings();
355         for (PredictedAppIcon icon : getPredictedIcons()) {
356             if (!icon.isEnabled()) {
357                 continue;
358             }
359             if (dragObject.dragSource == this && icon.equals(dragObject.originalView)) {
360                 removeIconWithoutNotify(icon);
361                 continue;
362             }
363             int rank = ((WorkspaceItemInfo) icon.getTag()).rank;
364             outlines.add(new PredictedAppIcon.PredictedIconOutlineDrawing(
365                     mHotseat.getCellXFromOrder(rank), mHotseat.getCellYFromOrder(rank), icon));
366             icon.setEnabled(false);
367             ObjectAnimator animator = ObjectAnimator.ofFloat(icon, SCALE_PROPERTY, 0);
368             animator.addListener(new AnimationSuccessListener() {
369                 @Override
370                 public void onAnimationSuccess(Animator animator) {
371                     if (icon.getParent() != null) {
372                         removeIconWithoutNotify(icon);
373                     }
374                 }
375             });
376             mIconRemoveAnimators.play(animator);
377         }
378         mIconRemoveAnimators.start();
379     }
380 
381     /**
382      * Removes icon while suppressing any extra tasks performed on view-hierarchy changes.
383      * This avoids recursive/redundant updates as the control updates the UI anyway after
384      * it's animation.
385      */
removeIconWithoutNotify(PredictedAppIcon icon)386     private void removeIconWithoutNotify(PredictedAppIcon icon) {
387         mPauseFlags |= FLAG_REMOVING_PREDICTED_ICON;
388         mHotseat.removeView(icon);
389         mPauseFlags &= ~FLAG_REMOVING_PREDICTED_ICON;
390     }
391 
392     @Override
onDragStart(DropTarget.DragObject dragObject, DragOptions options)393     public void onDragStart(DropTarget.DragObject dragObject, DragOptions options) {
394         removePredictedApps(mOutlineDrawings, dragObject);
395         if (mOutlineDrawings.isEmpty()) return;
396         for (PredictedAppIcon.PredictedIconOutlineDrawing outlineDrawing : mOutlineDrawings) {
397             mHotseat.addDelegatedCellDrawing(outlineDrawing);
398         }
399         mPauseFlags |= FLAG_DRAG_IN_PROGRESS;
400         mHotseat.invalidate();
401     }
402 
403     @Override
onDragEnd()404     public void onDragEnd() {
405         mPauseFlags &= ~FLAG_DRAG_IN_PROGRESS;
406         fillGapsWithPrediction(true);
407     }
408 
409     @Nullable
410     @Override
getShortcut(QuickstepLauncher activity, ItemInfo itemInfo)411     public SystemShortcut<QuickstepLauncher> getShortcut(QuickstepLauncher activity,
412             ItemInfo itemInfo) {
413         if (itemInfo.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION) {
414             return null;
415         }
416         return new PinPrediction(activity, itemInfo);
417     }
418 
preparePredictionInfo(WorkspaceItemInfo itemInfo, int rank)419     private void preparePredictionInfo(WorkspaceItemInfo itemInfo, int rank) {
420         itemInfo.container = LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION;
421         itemInfo.rank = rank;
422         itemInfo.cellX = mHotseat.getCellXFromOrder(rank);
423         itemInfo.cellY = mHotseat.getCellYFromOrder(rank);
424         itemInfo.screenId = rank;
425     }
426 
427     @Override
onDeviceProfileChanged(DeviceProfile profile)428     public void onDeviceProfileChanged(DeviceProfile profile) {
429         this.mHotSeatItemsCount = profile.numShownHotseatIcons;
430     }
431 
432     @Override
onDropCompleted(View target, DropTarget.DragObject d, boolean success)433     public void onDropCompleted(View target, DropTarget.DragObject d, boolean success) {
434         //Does nothing
435     }
436 
437     /**
438      * Logs rank info based on current list of predicted items
439      */
logLaunchedAppRankingInfo(@onNull ItemInfo itemInfo, InstanceId instanceId)440     public void logLaunchedAppRankingInfo(@NonNull ItemInfo itemInfo, InstanceId instanceId) {
441         ComponentName targetCN = itemInfo.getTargetComponent();
442         if (targetCN == null) {
443             return;
444         }
445         int rank = -1;
446         for (int i = mPredictedItems.size() - 1; i >= 0; i--) {
447             ItemInfo info = mPredictedItems.get(i);
448             if (targetCN.equals(info.getTargetComponent()) && itemInfo.user.equals(info.user)) {
449                 rank = i;
450                 break;
451             }
452         }
453         if (rank < 0) {
454             return;
455         }
456 
457         int cardinality = 0;
458         for (PredictedAppIcon icon : getPredictedIcons()) {
459             ItemInfo info = (ItemInfo) icon.getTag();
460             cardinality |= 1 << info.screenId;
461         }
462 
463         PredictedHotseatContainer.Builder containerBuilder = PredictedHotseatContainer.newBuilder();
464         containerBuilder.setCardinality(cardinality);
465         if (itemInfo.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION) {
466             containerBuilder.setIndex(rank);
467         }
468         mLauncher.getStatsLogManager().logger()
469                 .withInstanceId(instanceId)
470                 .withRank(rank)
471                 .withContainerInfo(ContainerInfo.newBuilder()
472                         .setPredictedHotseatContainer(containerBuilder)
473                         .build())
474                 .log(LAUNCHER_HOTSEAT_RANKED);
475     }
476 
477     /**
478      * Called when app/shortcut icon is removed by system. This is used to prune visible stale
479      * predictions while while waiting for AppAPrediction service to send new batch of predictions.
480      *
481      * @param matcher filter matching items that have been removed
482      */
onModelItemsRemoved(ItemInfoMatcher matcher)483     public void onModelItemsRemoved(ItemInfoMatcher matcher) {
484         if (mPredictedItems.removeIf(matcher::matchesInfo)) {
485             fillGapsWithPrediction(true);
486         }
487     }
488 
489     /**
490      * Called when user completes adding item requiring a config activity to the hotseat
491      */
onDeferredDrop(int cellX, int cellY)492     public void onDeferredDrop(int cellX, int cellY) {
493         View child = mHotseat.getChildAt(cellX, cellY);
494         if (child instanceof PredictedAppIcon) {
495             removeIconWithoutNotify((PredictedAppIcon) child);
496         }
497     }
498 
499     private class PinPrediction extends SystemShortcut<QuickstepLauncher> {
500 
PinPrediction(QuickstepLauncher target, ItemInfo itemInfo)501         private PinPrediction(QuickstepLauncher target, ItemInfo itemInfo) {
502             super(R.drawable.ic_pin, R.string.pin_prediction, target,
503                     itemInfo);
504         }
505 
506         @Override
onClick(View view)507         public void onClick(View view) {
508             dismissTaskMenuView(mTarget);
509             pinPrediction(mItemInfo);
510         }
511     }
512 
isPredictedIcon(View view)513     private static boolean isPredictedIcon(View view) {
514         return view instanceof PredictedAppIcon && view.getTag() instanceof WorkspaceItemInfo
515                 && ((WorkspaceItemInfo) view.getTag()).container
516                 == LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION;
517     }
518 }
519