1 /*
2  * Copyright (C) 2018 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.views;
17 
18 import static android.window.SplashScreen.SPLASH_SCREEN_STYLE_SOLID_COLOR;
19 
20 import static com.android.launcher3.BuildConfig.WIDGETS_ENABLED;
21 import static com.android.launcher3.LauncherSettings.Animation.DEFAULT_NO_ICON;
22 import static com.android.launcher3.Utilities.allowBGLaunch;
23 import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ALLAPPS_KEYBOARD_CLOSED;
24 import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_APP_LAUNCH_PENDING_INTENT;
25 import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_APP_LAUNCH_TAP;
26 import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
27 import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
28 
29 import android.app.ActivityOptions;
30 import android.app.PendingIntent;
31 import android.content.ActivityNotFoundException;
32 import android.content.Context;
33 import android.content.ContextWrapper;
34 import android.content.Intent;
35 import android.content.pm.LauncherApps;
36 import android.content.res.Configuration;
37 import android.graphics.Rect;
38 import android.graphics.drawable.Drawable;
39 import android.os.Bundle;
40 import android.os.IBinder;
41 import android.os.Process;
42 import android.os.UserHandle;
43 import android.util.Log;
44 import android.view.ContextThemeWrapper;
45 import android.view.Display;
46 import android.view.LayoutInflater;
47 import android.view.View;
48 import android.view.View.AccessibilityDelegate;
49 import android.view.WindowInsets;
50 import android.view.WindowInsetsController;
51 import android.view.inputmethod.InputMethodManager;
52 import android.widget.Toast;
53 
54 import androidx.annotation.NonNull;
55 import androidx.annotation.Nullable;
56 import androidx.core.view.WindowInsetsCompat;
57 
58 import com.android.launcher3.BubbleTextView;
59 import com.android.launcher3.DeviceProfile;
60 import com.android.launcher3.DeviceProfile.OnDeviceProfileChangeListener;
61 import com.android.launcher3.DropTargetHandler;
62 import com.android.launcher3.LauncherSettings;
63 import com.android.launcher3.R;
64 import com.android.launcher3.Utilities;
65 import com.android.launcher3.allapps.ActivityAllAppsContainerView;
66 import com.android.launcher3.celllayout.CellPosMapper;
67 import com.android.launcher3.dot.DotInfo;
68 import com.android.launcher3.dragndrop.DragController;
69 import com.android.launcher3.folder.FolderIcon;
70 import com.android.launcher3.logger.LauncherAtom;
71 import com.android.launcher3.logging.InstanceId;
72 import com.android.launcher3.logging.InstanceIdSequence;
73 import com.android.launcher3.logging.StatsLogManager;
74 import com.android.launcher3.model.StringCache;
75 import com.android.launcher3.model.data.ItemInfo;
76 import com.android.launcher3.model.data.WorkspaceItemInfo;
77 import com.android.launcher3.popup.PopupDataProvider;
78 import com.android.launcher3.util.ActivityOptionsWrapper;
79 import com.android.launcher3.util.PackageManagerHelper;
80 import com.android.launcher3.util.Preconditions;
81 import com.android.launcher3.util.RunnableList;
82 import com.android.launcher3.util.SplitConfigurationOptions;
83 import com.android.launcher3.util.ViewCache;
84 
85 import java.util.List;
86 
87 /**
88  * An interface to be used along with a context for various activities in Launcher. This allows a
89  * generic class to depend on Context subclass instead of an Activity.
90  */
91 public interface ActivityContext {
92 
93     String TAG = "ActivityContext";
94 
finishAutoCancelActionMode()95     default boolean finishAutoCancelActionMode() {
96         return false;
97     }
98 
getDotInfoForItem(ItemInfo info)99     default DotInfo getDotInfoForItem(ItemInfo info) {
100         return null;
101     }
102 
103     /**
104      * For items with tree hierarchy, notifies the activity to invalidate the parent when a root
105      * is invalidated
106      * @param info info associated with a root node.
107      */
invalidateParent(ItemInfo info)108     default void invalidateParent(ItemInfo info) { }
109 
getAccessibilityDelegate()110     default AccessibilityDelegate getAccessibilityDelegate() {
111         return null;
112     }
113 
getFolderBoundingBox()114     default Rect getFolderBoundingBox() {
115         return getDeviceProfile().getAbsoluteOpenFolderBounds();
116     }
117 
118     /**
119      * After calling {@link #getFolderBoundingBox()}, we calculate a (left, top) position for a
120      * Folder of size width x height to be within those bounds. However, the chosen position may
121      * not be visually ideal (e.g. uncanny valley of centeredness), so here's a chance to update it.
122      * @param inOutPosition A 2-size array where the first element is the left position of the open
123      *     folder and the second element is the top position. Should be updated in place if desired.
124      * @param bounds The bounds that the open folder should fit inside.
125      * @param width The width of the open folder.
126      * @param height The height of the open folder.
127      */
updateOpenFolderPosition(int[] inOutPosition, Rect bounds, int width, int height)128     default void updateOpenFolderPosition(int[] inOutPosition, Rect bounds, int width, int height) {
129     }
130 
131     /**
132      * Returns a LayoutInflater that is cloned in this Context, so that Views inflated by it will
133      * have the same Context. (i.e. {@link #lookupContext(Context)} will find this ActivityContext.)
134      */
getLayoutInflater()135     default LayoutInflater getLayoutInflater() {
136         if (this instanceof Context) {
137             Context context = (Context) this;
138             return LayoutInflater.from(context).cloneInContext(context);
139         }
140         return null;
141     }
142 
143     /** Called when the first app in split screen has been selected */
startSplitSelection( SplitConfigurationOptions.SplitSelectSource splitSelectSource)144     default void startSplitSelection(
145             SplitConfigurationOptions.SplitSelectSource splitSelectSource) {
146         // Overridden, intentionally empty
147     }
148 
149     /**
150      * @return {@code true} if user has selected the first split app and is in the process of
151      *         selecting the second
152      */
isSplitSelectionActive()153     default boolean isSplitSelectionActive() {
154         // Overridden
155         return false;
156     }
157 
158     /**
159      * Handle user tapping on unsupported target when in split selection mode.
160      * See {@link #isSplitSelectionActive()}
161      *
162      * @return {@code true} if this method will handle the incorrect target selection,
163      *         {@code false} if it could not be handled or if not possible to handle based on
164      *         current split state
165      */
handleIncorrectSplitTargetSelection()166     default boolean handleIncorrectSplitTargetSelection() {
167         // Overridden
168         return false;
169     }
170 
171     /**
172      * The root view to support drag-and-drop and popup support.
173      */
getDragLayer()174     BaseDragLayer getDragLayer();
175 
176     /**
177      * The all apps container, if it exists in this context.
178      */
getAppsView()179     default ActivityAllAppsContainerView<?> getAppsView() {
180         return null;
181     }
182 
getDeviceProfile()183     DeviceProfile getDeviceProfile();
184 
185     /** Registered {@link OnDeviceProfileChangeListener} instances. */
getOnDeviceProfileChangeListeners()186     List<OnDeviceProfileChangeListener> getOnDeviceProfileChangeListeners();
187 
188     /** Notifies listeners of a {@link DeviceProfile} change. */
dispatchDeviceProfileChanged()189     default void dispatchDeviceProfileChanged() {
190         DeviceProfile deviceProfile = getDeviceProfile();
191         List<OnDeviceProfileChangeListener> listeners = getOnDeviceProfileChangeListeners();
192         for (int i = listeners.size() - 1; i >= 0; i--) {
193             listeners.get(i).onDeviceProfileChanged(deviceProfile);
194         }
195     }
196 
197     /** Register listener for {@link DeviceProfile} changes. */
addOnDeviceProfileChangeListener(OnDeviceProfileChangeListener listener)198     default void addOnDeviceProfileChangeListener(OnDeviceProfileChangeListener listener) {
199         getOnDeviceProfileChangeListeners().add(listener);
200     }
201 
202     /** Unregister listener for {@link DeviceProfile} changes. */
removeOnDeviceProfileChangeListener(OnDeviceProfileChangeListener listener)203     default void removeOnDeviceProfileChangeListener(OnDeviceProfileChangeListener listener) {
204         getOnDeviceProfileChangeListeners().remove(listener);
205     }
206 
getViewCache()207     default ViewCache getViewCache() {
208         return new ViewCache();
209     }
210 
211     /**
212      * Controller for supporting item drag-and-drop
213      */
getDragController()214     default <T extends DragController> T getDragController() {
215         return null;
216     }
217 
218     /**
219      * Handler for actions taken on drop targets that require launcher
220      */
getDropTargetHandler()221     default DropTargetHandler getDropTargetHandler() {
222         return null;
223     }
224 
225     /**
226      * Returns the FolderIcon with the given item id, if it exists.
227      */
findFolderIcon(final int folderIconId)228     default @Nullable FolderIcon findFolderIcon(final int folderIconId) {
229         return null;
230     }
231 
getStatsLogManager()232     default StatsLogManager getStatsLogManager() {
233         return StatsLogManager.newInstance((Context) this);
234     }
235 
236     /**
237      * Returns {@code true} if popups can use a range of color shades instead of a singular color.
238      */
canUseMultipleShadesForPopup()239     default boolean canUseMultipleShadesForPopup() {
240         return true;
241     }
242 
243     /**
244      * Called just before logging the given item.
245      */
applyOverwritesToLogItem(LauncherAtom.ItemInfo.Builder itemInfoBuilder)246     default void applyOverwritesToLogItem(LauncherAtom.ItemInfo.Builder itemInfoBuilder) { }
247 
248     /** Returns {@code true} if items are currently being bound within this context. */
isBindingItems()249     default boolean isBindingItems() {
250         return false;
251     }
252 
getItemOnClickListener()253     default View.OnClickListener getItemOnClickListener() {
254         return v -> {
255             // No op.
256         };
257     }
258 
259     /** Long-click callback used for All Apps items. */
getAllAppsItemLongClickListener()260     default View.OnLongClickListener getAllAppsItemLongClickListener() {
261         return v -> false;
262     }
263 
264     @Nullable
getPopupDataProvider()265     default PopupDataProvider getPopupDataProvider() {
266         return null;
267     }
268 
269     @Nullable
getStringCache()270     default StringCache getStringCache() {
271         return null;
272     }
273 
274     /**
275      * Hides the keyboard if it is visible
276      */
hideKeyboard()277     default void hideKeyboard() {
278         View root = getDragLayer();
279         if (root == null) {
280             return;
281         }
282         Preconditions.assertUIThread();
283         // Hide keyboard with WindowInsetsController if could. In case hideSoftInputFromWindow may
284         // get ignored by input connection being finished when the screen is off.
285         //
286         // In addition, inside IMF, the keyboards are closed asynchronously that launcher no longer
287         // need to post to the message queue.
288         final WindowInsetsController wic = root.getWindowInsetsController();
289         WindowInsets insets = root.getRootWindowInsets();
290         boolean isImeShown = insets != null && insets.isVisible(WindowInsets.Type.ime());
291         if (wic != null) {
292             // Only hide the keyboard if it is actually showing.
293             if (isImeShown) {
294                 // this method cannot be called cross threads
295                 wic.hide(WindowInsets.Type.ime());
296                 getStatsLogManager().logger().log(LAUNCHER_ALLAPPS_KEYBOARD_CLOSED);
297             }
298 
299             // If the WindowInsetsController is not null, we end here regardless of whether we hid
300             // the keyboard or not.
301             return;
302         }
303 
304         InputMethodManager imm = root.getContext().getSystemService(InputMethodManager.class);
305         IBinder token = root.getWindowToken();
306         if (imm != null && token != null) {
307             UI_HELPER_EXECUTOR.execute(() -> {
308                 if (imm.hideSoftInputFromWindow(token, 0)) {
309                     // log keyboard close event only when keyboard is actually closed
310                     MAIN_EXECUTOR.execute(() ->
311                             getStatsLogManager().logger().log(LAUNCHER_ALLAPPS_KEYBOARD_CLOSED));
312                 }
313             });
314         }
315     }
316 
317     /**
318      * Returns if the connected keyboard is a hardware keyboard.
319      */
isHardwareKeyboard()320     default boolean isHardwareKeyboard() {
321         return Configuration.KEYBOARD_QWERTY
322                 == ((Context) this).getResources().getConfiguration().keyboard;
323     }
324 
325     /**
326      * Returns if the software keyboard (including input toolbar) is hidden. Hardware
327      * keyboards do not display on screen by default.
328      */
isSoftwareKeyboardHidden()329     default boolean isSoftwareKeyboardHidden() {
330         if (isHardwareKeyboard()) {
331             return true;
332         } else {
333             View dragLayer = getDragLayer();
334             WindowInsets insets = dragLayer.getRootWindowInsets();
335             if (insets == null) {
336                 return false;
337             }
338             WindowInsetsCompat insetsCompat =
339                     WindowInsetsCompat.toWindowInsetsCompat(insets, dragLayer);
340             return !insetsCompat.isVisible(WindowInsetsCompat.Type.ime());
341         }
342     }
343 
344     /**
345      * Sends a pending intent animating from a view.
346      *
347      * @param v View to animate.
348      * @param intent The pending intent being launched.
349      * @param item Item associated with the view.
350      * @return RunnableList for listening for animation finish if the activity was properly
351      *         or started, {@code null} if the launch finished
352      */
sendPendingIntentWithAnimation( @onNull View v, PendingIntent intent, @Nullable ItemInfo item)353     default RunnableList sendPendingIntentWithAnimation(
354             @NonNull View v, PendingIntent intent, @Nullable ItemInfo item) {
355         ActivityOptionsWrapper options = getActivityLaunchOptions(v, item);
356         try {
357             intent.send(null, 0, null, null, null, null, options.toBundle());
358             if (item != null) {
359                 InstanceId instanceId = new InstanceIdSequence().newInstanceId();
360                 getStatsLogManager().logger().withItemInfo(item).withInstanceId(instanceId)
361                         .log(LAUNCHER_APP_LAUNCH_PENDING_INTENT);
362             }
363             return options.onEndCallback;
364         } catch (PendingIntent.CanceledException e) {
365             Toast.makeText(v.getContext(),
366                     v.getContext().getResources().getText(R.string.shortcut_not_available),
367                     Toast.LENGTH_SHORT).show();
368         }
369         return null;
370     }
371 
372     /**
373      * Safely starts an activity.
374      *
375      * @param v View starting the activity.
376      * @param intent Base intent being launched.
377      * @param item Item associated with the view.
378      * @return RunnableList for listening for animation finish if the activity was properly
379      *         or started, {@code null} if the launch finished
380      */
startActivitySafely( View v, Intent intent, @Nullable ItemInfo item)381     default RunnableList startActivitySafely(
382             View v, Intent intent, @Nullable ItemInfo item) {
383         Preconditions.assertUIThread();
384         Context context = (Context) this;
385         if (isAppBlockedForSafeMode() && !PackageManagerHelper.isSystemApp(context, intent)) {
386             Toast.makeText(context, R.string.safemode_shortcut_error, Toast.LENGTH_SHORT).show();
387             return null;
388         }
389 
390         boolean isShortcut = (item instanceof WorkspaceItemInfo)
391                 && item.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT
392                 && !((WorkspaceItemInfo) item).isPromise();
393         if (isShortcut && !WIDGETS_ENABLED) {
394             return null;
395         }
396         ActivityOptionsWrapper options = v != null ? getActivityLaunchOptions(v, item)
397                 : makeDefaultActivityOptions(item != null && item.animationType == DEFAULT_NO_ICON
398                         ? SPLASH_SCREEN_STYLE_SOLID_COLOR : -1 /* SPLASH_SCREEN_STYLE_UNDEFINED */);
399         UserHandle user = item == null ? null : item.user;
400         Bundle optsBundle = options.toBundle();
401         // Prepare intent
402         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
403         if (v != null) {
404             intent.setSourceBounds(Utilities.getViewBounds(v));
405         }
406         try {
407             if (isShortcut) {
408                 String id = ((WorkspaceItemInfo) item).getDeepShortcutId();
409                 String packageName = intent.getPackage();
410                 ((Context) this).getSystemService(LauncherApps.class).startShortcut(
411                         packageName, id, intent.getSourceBounds(), optsBundle, user);
412             } else if (user == null || user.equals(Process.myUserHandle())) {
413                 // Could be launching some bookkeeping activity
414                 context.startActivity(intent, optsBundle);
415             } else {
416                 context.getSystemService(LauncherApps.class).startMainActivity(
417                         intent.getComponent(), user, intent.getSourceBounds(), optsBundle);
418             }
419             if (item != null) {
420                 InstanceId instanceId = new InstanceIdSequence().newInstanceId();
421                 logAppLaunch(getStatsLogManager(), item, instanceId);
422             }
423             return options.onEndCallback;
424         } catch (NullPointerException | ActivityNotFoundException | SecurityException e) {
425             Toast.makeText(context, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
426             Log.e(TAG, "Unable to launch. tag=" + item + " intent=" + intent, e);
427         }
428         return null;
429     }
430 
431     /** Returns {@code true} if an app launch is blocked due to safe mode. */
isAppBlockedForSafeMode()432     default boolean isAppBlockedForSafeMode() {
433         return false;
434     }
435 
436     /**
437      * Creates and logs a new app launch event.
438      */
logAppLaunch(StatsLogManager statsLogManager, ItemInfo info, InstanceId instanceId)439     default void logAppLaunch(StatsLogManager statsLogManager, ItemInfo info,
440             InstanceId instanceId) {
441         statsLogManager.logger().withItemInfo(info).withInstanceId(instanceId)
442                 .log(LAUNCHER_APP_LAUNCH_TAP);
443     }
444 
445     /**
446      * Returns launch options for an Activity.
447      *
448      * @param v View initiating a launch.
449      * @param item Item associated with the view.
450      */
getActivityLaunchOptions(View v, @Nullable ItemInfo item)451     default ActivityOptionsWrapper getActivityLaunchOptions(View v, @Nullable ItemInfo item) {
452         int left = 0, top = 0;
453         int width = v.getMeasuredWidth(), height = v.getMeasuredHeight();
454         if (v instanceof BubbleTextView) {
455             // Launch from center of icon, not entire view
456             Drawable icon = ((BubbleTextView) v).getIcon();
457             if (icon != null) {
458                 Rect bounds = icon.getBounds();
459                 left = (width - bounds.width()) / 2;
460                 top = v.getPaddingTop();
461                 width = bounds.width();
462                 height = bounds.height();
463             }
464         }
465         ActivityOptions options =
466                 allowBGLaunch(ActivityOptions.makeClipRevealAnimation(v, left, top, width, height));
467         options.setLaunchDisplayId(
468                 (v != null && v.getDisplay() != null) ? v.getDisplay().getDisplayId()
469                         : Display.DEFAULT_DISPLAY);
470         RunnableList callback = new RunnableList();
471         return new ActivityOptionsWrapper(options, callback);
472     }
473 
474     /**
475      * Creates a default activity option and we do not want association with any launcher element.
476      */
makeDefaultActivityOptions(int splashScreenStyle)477     default ActivityOptionsWrapper makeDefaultActivityOptions(int splashScreenStyle) {
478         ActivityOptions options = allowBGLaunch(ActivityOptions.makeBasic());
479         if (Utilities.ATLEAST_T) {
480             options.setSplashScreenStyle(splashScreenStyle);
481         }
482         return new ActivityOptionsWrapper(options, new RunnableList());
483     }
484 
getCellPosMapper()485     default CellPosMapper getCellPosMapper() {
486         DeviceProfile dp = getDeviceProfile();
487         return new CellPosMapper(dp.isVerticalBarLayout(), dp.numShownHotseatIcons);
488     }
489 
490     /** Whether bubbles are enabled. */
isBubbleBarEnabled()491     default boolean isBubbleBarEnabled() {
492         return false;
493     }
494 
495     /** Whether the bubble bar has bubbles. */
hasBubbles()496     default boolean hasBubbles() {
497         return false;
498     }
499 
500     /**
501      * Returns the ActivityContext associated with the given Context, or throws an exception if
502      * the Context is not associated with any ActivityContext.
503      */
lookupContext(Context context)504     static <T extends Context & ActivityContext> T lookupContext(Context context) {
505         T activityContext = lookupContextNoThrow(context);
506         if (activityContext == null) {
507             throw new IllegalArgumentException("Cannot find ActivityContext in parent tree");
508         }
509         return activityContext;
510     }
511 
512     /**
513      * Returns the ActivityContext associated with the given Context, or null if
514      * the Context is not associated with any ActivityContext.
515      */
lookupContextNoThrow(Context context)516     static <T extends Context & ActivityContext> T lookupContextNoThrow(Context context) {
517         if (context instanceof ActivityContext) {
518             return (T) context;
519         } else if (context instanceof ActivityContextDelegate acd) {
520             return (T) acd.mDelegate;
521         } else if (context instanceof ContextWrapper) {
522             return lookupContextNoThrow(((ContextWrapper) context).getBaseContext());
523         } else {
524             return null;
525         }
526     }
527 
528     class ActivityContextDelegate extends ContextThemeWrapper {
529         public final ActivityContext mDelegate;
530 
ActivityContextDelegate(Context base, int themeResId, ActivityContext delegate)531         public ActivityContextDelegate(Context base, int themeResId, ActivityContext delegate) {
532             super(base, themeResId);
533             mDelegate = delegate;
534         }
535     }
536 }
537