2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.launcher3;
19 import android.animation.Animator;
20 import android.animation.AnimatorListenerAdapter;
21 import android.animation.AnimatorSet;
22 import android.animation.ObjectAnimator;
23 import android.animation.PropertyValuesHolder;
24 import android.animation.ValueAnimator;
25 import android.annotation.SuppressLint;
26 import android.annotation.TargetApi;
27 import android.app.Activity;
28 import android.app.ActivityManager;
29 import android.app.ActivityOptions;
30 import android.app.AlertDialog;
31 import android.app.SearchManager;
32 import android.appwidget.AppWidgetHostView;
33 import android.appwidget.AppWidgetManager;
34 import android.appwidget.AppWidgetProviderInfo;
35 import android.content.ActivityNotFoundException;
36 import android.content.BroadcastReceiver;
37 import android.content.ComponentCallbacks2;
38 import android.content.ComponentName;
39 import android.content.Context;
40 import android.content.DialogInterface;
41 import android.content.Intent;
42 import android.content.IntentFilter;
43 import android.content.IntentSender;
44 import android.content.SharedPreferences;
45 import android.content.pm.ActivityInfo;
46 import android.content.pm.ApplicationInfo;
47 import android.content.pm.PackageManager;
48 import android.content.pm.PackageManager.NameNotFoundException;
49 import android.content.res.Configuration;
50 import android.database.sqlite.SQLiteDatabase;
51 import android.graphics.Bitmap;
52 import android.graphics.Canvas;
53 import android.graphics.Color;
54 import android.graphics.PorterDuff;
55 import android.graphics.Rect;
56 import android.graphics.drawable.ColorDrawable;
57 import android.graphics.drawable.Drawable;
58 import android.net.Uri;
59 import android.os.AsyncTask;
60 import android.os.Build;
61 import android.os.Bundle;
62 import android.os.Environment;
63 import android.os.Handler;
64 import android.os.Message;
65 import android.os.StrictMode;
66 import android.os.SystemClock;
67 import android.os.UserHandle;
68 import android.text.Selection;
69 import android.text.SpannableStringBuilder;
70 import android.text.TextUtils;
71 import android.text.method.TextKeyListener;
72 import android.util.Log;
73 import android.view.Display;
74 import android.view.Gravity;
75 import android.view.HapticFeedbackConstants;
76 import android.view.KeyEvent;
77 import android.view.LayoutInflater;
78 import android.view.Menu;
79 import android.view.MotionEvent;
80 import android.view.Surface;
81 import android.view.View;
82 import android.view.View.OnClickListener;
83 import android.view.View.OnLongClickListener;
84 import android.view.ViewGroup;
85 import android.view.ViewStub;
86 import android.view.ViewTreeObserver;
87 import android.view.Window;
88 import android.view.WindowManager;
89 import android.view.accessibility.AccessibilityEvent;
90 import android.view.animation.OvershootInterpolator;
91 import android.view.inputmethod.InputMethodManager;
92 import android.widget.Advanceable;
93 import android.widget.FrameLayout;
94 import android.widget.ImageView;
95 import android.widget.TextView;
96 import android.widget.Toast;
98 import com.android.launcher3.DropTarget.DragObject;
99 import com.android.launcher3.PagedView.PageSwitchListener;
100 import com.android.launcher3.allapps.AllAppsContainerView;
101 import com.android.launcher3.compat.AppWidgetManagerCompat;
102 import com.android.launcher3.compat.LauncherActivityInfoCompat;
103 import com.android.launcher3.compat.LauncherAppsCompat;
104 import com.android.launcher3.compat.UserHandleCompat;
105 import com.android.launcher3.compat.UserManagerCompat;
106 import com.android.launcher3.model.WidgetsModel;
107 import com.android.launcher3.util.ComponentKey;
108 import com.android.launcher3.util.LongArrayMap;
109 import com.android.launcher3.util.Thunk;
110 import com.android.launcher3.widget.PendingAddWidgetInfo;
111 import com.android.launcher3.widget.WidgetHostViewLoader;
112 import com.android.launcher3.widget.WidgetsContainerView;
115 import java.io.FileDescriptor;
116 import java.io.FileOutputStream;
117 import java.io.IOException;
118 import java.io.PrintWriter;
119 import java.text.DateFormat;
120 import java.util.ArrayList;
121 import java.util.Collection;
122 import java.util.Date;
123 import java.util.HashMap;
124 import java.util.HashSet;
125 import java.util.List;
126 import java.util.concurrent.atomic.AtomicInteger;
129 * Default launcher application.
131 public class Launcher extends Activity
132 implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
133 View.OnTouchListener, PageSwitchListener, LauncherProviderChangeListener {
134 static final String TAG = "Launcher";
135 static final boolean LOGD = false;
137 static final boolean PROFILE_STARTUP = false;
138 static final boolean DEBUG_WIDGETS = true;
139 static final boolean DEBUG_STRICT_MODE = false;
140 static final boolean DEBUG_RESUME_TIME = false;
141 static final boolean DEBUG_DUMP_LOG = false;
143 static final boolean ENABLE_DEBUG_INTENTS = false; // allow DebugIntents to run
145 private static final int REQUEST_CREATE_SHORTCUT = 1;
146 private static final int REQUEST_CREATE_APPWIDGET = 5;
147 private static final int REQUEST_PICK_APPWIDGET = 9;
148 private static final int REQUEST_PICK_WALLPAPER = 10;
150 private static final int REQUEST_BIND_APPWIDGET = 11;
151 private static final int REQUEST_RECONFIGURE_APPWIDGET = 12;
153 private static final int WORKSPACE_BACKGROUND_GRADIENT = 0;
154 private static final int WORKSPACE_BACKGROUND_TRANSPARENT = 1;
155 private static final int WORKSPACE_BACKGROUND_BLACK = 2;
157 private static final float BOUNCE_ANIMATION_TENSION = 1.3f;
160 * IntentStarter uses request codes starting with this. This must be greater than all activity
161 * request codes used internally.
163 protected static final int REQUEST_LAST = 100;
165 static final int SCREEN_COUNT = 5;
167 // To turn on these properties, type
168 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
169 static final String DUMP_STATE_PROPERTY = "launcher_dump_state";
171 // The Intent extra that defines whether to ignore the launch animation
172 static final String INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION =
173 "com.android.launcher3.intent.extra.shortcut.INGORE_LAUNCH_ANIMATION";
176 private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
178 private static final String RUNTIME_STATE = "launcher.state";
180 private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container";
182 private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
184 private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x";
186 private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y";
188 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_span_x";
190 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_span_y";
192 private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_INFO = "launcher.add_widget_info";
194 private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_ID = "launcher.add_widget_id";
196 private static final String RUNTIME_STATE_VIEW_IDS = "launcher.view_ids";
198 static final String INTRO_SCREEN_DISMISSED = "launcher.intro_screen_dismissed";
199 static final String FIRST_RUN_ACTIVITY_DISPLAYED = "launcher.first_run_activity_displayed";
201 static final String FIRST_LOAD_COMPLETE = "launcher.first_load_complete";
202 static final String ACTION_FIRST_LOAD_COMPLETE =
203 "com.android.launcher3.action.FIRST_LOAD_COMPLETE";
205 public static final String SHOW_WEIGHT_WATCHER = "debug.show_mem";
206 public static final boolean SHOW_WEIGHT_WATCHER_DEFAULT = false;
208 private static final String QSB_WIDGET_ID = "qsb_widget_id";
209 private static final String QSB_WIDGET_PROVIDER = "qsb_widget_provider";
211 public static final String USER_HAS_MIGRATED = "launcher.user_migrated_from_old_data";
213 /** The different states that Launcher can be in. */
214 enum State { NONE, WORKSPACE, APPS, APPS_SPRING_LOADED, WIDGETS, WIDGETS_SPRING_LOADED }
216 @Thunk State mState = State.WORKSPACE;
217 @Thunk LauncherStateTransitionAnimation mStateTransitionAnimation;
219 private boolean mIsSafeModeEnabled;
221 LauncherOverlayCallbacks mLauncherOverlayCallbacks = new LauncherOverlayCallbacksImpl();
222 LauncherOverlay mLauncherOverlay;
223 InsettableFrameLayout mLauncherOverlayContainer;
225 static final int APPWIDGET_HOST_ID = 1024;
226 public static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300;
227 private static final int ON_ACTIVITY_RESULT_ANIMATION_DELAY = 500;
228 private static final int ACTIVITY_START_DELAY = 1000;
230 private HashMap<Integer, Integer> mItemIdToViewId = new HashMap<Integer, Integer>();
231 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
233 // How long to wait before the new-shortcut animation automatically pans the workspace
234 private static int NEW_APPS_PAGE_MOVE_DELAY = 500;
235 private static int NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS = 5;
236 @Thunk static int NEW_APPS_ANIMATION_DELAY = 500;
238 private final BroadcastReceiver mCloseSystemDialogsReceiver
239 = new CloseSystemDialogsIntentReceiver();
241 private LayoutInflater mInflater;
243 @Thunk Workspace mWorkspace;
244 private View mLauncherView;
245 private View mPageIndicators;
246 @Thunk DragLayer mDragLayer;
247 private DragController mDragController;
248 private View mWeightWatcher;
250 private AppWidgetManagerCompat mAppWidgetManager;
251 private LauncherAppWidgetHost mAppWidgetHost;
253 @Thunk ItemInfo mPendingAddInfo = new ItemInfo();
254 private LauncherAppWidgetProviderInfo mPendingAddWidgetInfo;
255 private int mPendingAddWidgetId = -1;
257 private int[] mTmpAddItemCellCoordinates = new int[2];
259 @Thunk Hotseat mHotseat;
260 private ViewGroup mOverviewPanel;
262 private View mAllAppsButton;
263 private View mWidgetsButton;
265 private SearchDropTargetBar mSearchDropTargetBar;
267 // Main container view for the all apps screen.
268 @Thunk AllAppsContainerView mAppsView;
270 // Main container view and the model for the widget tray screen.
271 @Thunk WidgetsContainerView mWidgetsView;
272 @Thunk WidgetsModel mWidgetsModel;
274 private boolean mAutoAdvanceRunning = false;
275 private AppWidgetHostView mQsb;
277 private Bundle mSavedState;
278 // We set the state in both onCreate and then onNewIntent in some cases, which causes both
279 // scroll issues (because the workspace may not have been measured yet) and extra work.
280 // Instead, just save the state that we need to restore Launcher to, and commit it in onResume.
281 private State mOnResumeState = State.NONE;
283 private SpannableStringBuilder mDefaultKeySsb = null;
285 @Thunk boolean mWorkspaceLoading = true;
287 private boolean mPaused = true;
288 private boolean mRestoring;
289 private boolean mWaitingForResult;
290 private boolean mOnResumeNeedsLoad;
292 private ArrayList<Runnable> mBindOnResumeCallbacks = new ArrayList<Runnable>();
293 private ArrayList<Runnable> mOnResumeCallbacks = new ArrayList<Runnable>();
295 private Bundle mSavedInstanceState;
297 private LauncherModel mModel;
298 private IconCache mIconCache;
299 @Thunk boolean mUserPresent = true;
300 private boolean mVisible = false;
301 private boolean mHasFocus = false;
302 private boolean mAttached = false;
304 private LauncherClings mClings;
306 private static LongArrayMap<FolderInfo> sFolders = new LongArrayMap<>();
308 private View.OnTouchListener mHapticFeedbackTouchListener;
310 // Related to the auto-advancing of widgets
311 private final int ADVANCE_MSG = 1;
312 private final int mAdvanceInterval = 20000;
313 private final int mAdvanceStagger = 250;
314 private long mAutoAdvanceSentTime;
315 private long mAutoAdvanceTimeLeft = -1;
316 @Thunk HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance =
317 new HashMap<View, AppWidgetProviderInfo>();
319 // Determines how long to wait after a rotation before restoring the screen orientation to
320 // match the sensor state.
321 private final int mRestoreScreenOrientationDelay = 500;
323 @Thunk Drawable mWorkspaceBackgroundDrawable;
325 private final ArrayList<Integer> mSynchronouslyBoundPages = new ArrayList<Integer>();
326 private static final boolean DISABLE_SYNCHRONOUS_BINDING_CURRENT_PAGE = false;
328 static final ArrayList<String> sDumpLogs = new ArrayList<String>();
329 static Date sDateStamp = new Date();
330 static DateFormat sDateFormat =
331 DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
332 static long sRunStart = System.currentTimeMillis();
333 static final String CORRUPTION_EMAIL_SENT_KEY = "corruptionEmailSent";
335 // We only want to get the SharedPreferences once since it does an FS stat each time we get
336 // it from the context.
337 private SharedPreferences mSharedPrefs;
339 // Holds the page that we need to animate to, and the icon views that we need to animate up
340 // when we scroll to that page on resume.
341 @Thunk ImageView mFolderIconImageView;
342 private Bitmap mFolderIconBitmap;
343 private Canvas mFolderIconCanvas;
344 private Rect mRectForFolderAnimation = new Rect();
346 private DeviceProfile mDeviceProfile;
348 // This is set to the view that launched the activity that navigated the user away from
349 // launcher. Since there is no callback for when the activity has finished launching, enable
350 // the press state and keep this reference to reset the press state when we return to launcher.
351 private BubbleTextView mWaitingForResume;
353 protected static HashMap<String, CustomAppWidget> sCustomAppWidgets =
354 new HashMap<String, CustomAppWidget>();
356 private static final boolean ENABLE_CUSTOM_WIDGET_TEST = false;
358 if (ENABLE_CUSTOM_WIDGET_TEST) {
359 sCustomAppWidgets.put(DummyWidget.class.getName(), new DummyWidget());
363 @Thunk Runnable mBuildLayersRunnable = new Runnable() {
365 if (mWorkspace != null) {
366 mWorkspace.buildPageHardwareLayers();
371 private static PendingAddArguments sPendingAddItem;
373 @Thunk static class PendingAddArguments {
383 private Stats mStats;
384 FocusIndicatorView mFocusHandler;
385 private boolean mRotationEnabled = false;
387 @Thunk void setOrientation() {
388 if (mRotationEnabled) {
389 unlockScreenOrientation(true);
391 setRequestedOrientation(
392 ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
396 private Runnable mUpdateOrientationRunnable = new Runnable() {
403 protected void onCreate(Bundle savedInstanceState) {
404 if (DEBUG_STRICT_MODE) {
405 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
408 .detectNetwork() // or .detectAll() for all detectable problems
411 StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
412 .detectLeakedSqlLiteObjects()
413 .detectLeakedClosableObjects()
419 if (mLauncherCallbacks != null) {
420 mLauncherCallbacks.preOnCreate();
423 super.onCreate(savedInstanceState);
425 LauncherAppState.setApplicationContext(getApplicationContext());
426 LauncherAppState app = LauncherAppState.getInstance();
428 // Load configuration-specific DeviceProfile
429 mDeviceProfile = getResources().getConfiguration().orientation
430 == Configuration.ORIENTATION_LANDSCAPE ?
431 app.getInvariantDeviceProfile().landscapeProfile
432 : app.getInvariantDeviceProfile().portraitProfile;
434 mSharedPrefs = getSharedPreferences(LauncherAppState.getSharedPreferencesKey(),
435 Context.MODE_PRIVATE);
436 mIsSafeModeEnabled = getPackageManager().isSafeMode();
437 mModel = app.setLauncher(this);
438 mIconCache = app.getIconCache();
440 mDragController = new DragController(this);
441 mInflater = getLayoutInflater();
442 mStateTransitionAnimation = new LauncherStateTransitionAnimation(this);
444 mStats = new Stats(this);
446 mAppWidgetManager = AppWidgetManagerCompat.getInstance(this);
448 mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
449 mAppWidgetHost.startListening();
451 // If we are getting an onCreate, we can actually preempt onResume and unset mPaused here,
452 // this also ensures that any synchronous binding below doesn't re-trigger another
453 // LauncherModel load.
456 if (PROFILE_STARTUP) {
457 android.os.Debug.startMethodTracing(
458 Environment.getExternalStorageDirectory() + "/launcher");
461 setContentView(R.layout.launcher);
464 mDeviceProfile.layout(this);
468 mSavedState = savedInstanceState;
469 restoreState(mSavedState);
471 if (PROFILE_STARTUP) {
472 android.os.Debug.stopMethodTracing();
476 if (DISABLE_SYNCHRONOUS_BINDING_CURRENT_PAGE) {
477 // If the user leaves launcher, then we should just load items asynchronously when
479 mModel.startLoader(PagedView.INVALID_RESTORE_PAGE);
481 // We only load the page synchronously if the user rotates (or triggers a
482 // configuration change) while launcher is in the foreground
483 mModel.startLoader(mWorkspace.getRestorePage());
487 // For handling default keys
488 mDefaultKeySsb = new SpannableStringBuilder();
489 Selection.setSelection(mDefaultKeySsb, 0);
491 IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
492 registerReceiver(mCloseSystemDialogsReceiver, filter);
494 mRotationEnabled = Utilities.isRotationAllowedForDevice(getApplicationContext());
495 // In case we are on a device with locked rotation, we should look at preferences to check
496 // if the user has specifically allowed rotation.
497 if (!mRotationEnabled) {
498 mRotationEnabled = Utilities.isAllowRotationPrefEnabled(getApplicationContext(), false);
501 // On large interfaces, or on devices that a user has specifically enabled screen rotation,
502 // we want the screen to auto-rotate based on the current orientation
505 if (mLauncherCallbacks != null) {
506 mLauncherCallbacks.onCreate(savedInstanceState);
507 if (mLauncherCallbacks.hasLauncherOverlay()) {
508 ViewStub stub = (ViewStub) findViewById(R.id.launcher_overlay_stub);
509 mLauncherOverlayContainer = (InsettableFrameLayout) stub.inflate();
510 mLauncherOverlay = mLauncherCallbacks.setLauncherOverlayView(
511 mLauncherOverlayContainer, mLauncherOverlayCallbacks);
512 mWorkspace.setLauncherOverlay(mLauncherOverlay);
516 if (shouldShowIntroScreen()) {
519 showFirstRunActivity();
520 showFirstRunClings();
525 public void onSettingsChanged(String settings, boolean value) {
526 if (Utilities.ALLOW_ROTATION_PREFERENCE_KEY.equals(settings)) {
527 mRotationEnabled = value;
528 if (!waitUntilResume(mUpdateOrientationRunnable, true)) {
529 mUpdateOrientationRunnable.run();
534 private LauncherCallbacks mLauncherCallbacks;
536 public void onPostCreate(Bundle savedInstanceState) {
537 super.onPostCreate(savedInstanceState);
538 if (mLauncherCallbacks != null) {
539 mLauncherCallbacks.onPostCreate(savedInstanceState);
543 public boolean setLauncherCallbacks(LauncherCallbacks callbacks) {
544 mLauncherCallbacks = callbacks;
545 mLauncherCallbacks.setLauncherSearchCallback(new Launcher.LauncherSearchCallbacks() {
546 private boolean mWorkspaceImportanceStored = false;
547 private boolean mHotseatImportanceStored = false;
548 private int mWorkspaceImportanceForAccessibility =
549 View.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
550 private int mHotseatImportanceForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
553 public void onSearchOverlayOpened() {
554 if (mWorkspaceImportanceStored || mHotseatImportanceStored) {
557 // The underlying workspace and hotseat are temporarily suppressed by the search
558 // overlay. So they sholudn't be accessible.
559 if (mWorkspace != null) {
560 mWorkspaceImportanceForAccessibility =
561 mWorkspace.getImportantForAccessibility();
562 mWorkspace.setImportantForAccessibility(
563 View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
564 mWorkspaceImportanceStored = true;
566 if (mHotseat != null) {
567 mHotseatImportanceForAccessibility = mHotseat.getImportantForAccessibility();
568 mHotseat.setImportantForAccessibility(
569 View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
570 mHotseatImportanceStored = true;
575 public void onSearchOverlayClosed() {
576 if (mWorkspaceImportanceStored && mWorkspace != null) {
577 mWorkspace.setImportantForAccessibility(mWorkspaceImportanceForAccessibility);
579 if (mHotseatImportanceStored && mHotseat != null) {
580 mHotseat.setImportantForAccessibility(mHotseatImportanceForAccessibility);
582 mWorkspaceImportanceStored = false;
583 mHotseatImportanceStored = false;
590 public void onLauncherProviderChange() {
591 if (mLauncherCallbacks != null) {
592 mLauncherCallbacks.onLauncherProviderChange();
597 * Updates the bounds of all the overlays to match the new fixed bounds.
599 public void updateOverlayBounds(Rect newBounds) {
600 mAppsView.setSearchBarBounds(newBounds);
601 mWidgetsView.setSearchBarBounds(newBounds);
604 /** To be overridden by subclasses to hint to Launcher that we have custom content */
605 protected boolean hasCustomContentToLeft() {
606 if (mLauncherCallbacks != null) {
607 return mLauncherCallbacks.hasCustomContentToLeft();
613 * To be overridden by subclasses to populate the custom content container and call
614 * {@link #addToCustomContentPage}. This will only be invoked if
615 * {@link #hasCustomContentToLeft()} is {@code true}.
617 protected void populateCustomContentContainer() {
618 if (mLauncherCallbacks != null) {
619 mLauncherCallbacks.populateCustomContentContainer();
624 * Invoked by subclasses to signal a change to the {@link #addCustomContentToLeft} value to
625 * ensure the custom content page is added or removed if necessary.
627 protected void invalidateHasCustomContentToLeft() {
628 if (mWorkspace == null || mWorkspace.getScreenOrder().isEmpty()) {
629 // Not bound yet, wait for bindScreens to be called.
633 if (!mWorkspace.hasCustomContent() && hasCustomContentToLeft()) {
634 // Create the custom content page and call the subclass to populate it.
635 mWorkspace.createCustomContentContainer();
636 populateCustomContentContainer();
637 } else if (mWorkspace.hasCustomContent() && !hasCustomContentToLeft()) {
638 mWorkspace.removeCustomContentPage();
642 public Stats getStats() {
646 public LayoutInflater getInflater() {
650 public boolean isDraggingEnabled() {
651 // We prevent dragging when we are loading the workspace as it is possible to pick up a view
652 // that is subsequently removed from the workspace in startBinding().
653 return !isWorkspaceLoading();
656 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
657 public static int generateViewId() {
658 if (Utilities.ATLEAST_JB_MR1) {
659 return View.generateViewId();
661 // View.generateViewId() is not available. The following fallback logic is a copy
662 // of its implementation.
664 final int result = sNextGeneratedId.get();
665 // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
666 int newValue = result + 1;
667 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
668 if (sNextGeneratedId.compareAndSet(result, newValue)) {
675 public int getViewIdForItem(ItemInfo info) {
676 // This cast is safe given the > 2B range for int.
677 int itemId = (int) info.id;
678 if (mItemIdToViewId.containsKey(itemId)) {
679 return mItemIdToViewId.get(itemId);
681 int viewId = generateViewId();
682 mItemIdToViewId.put(itemId, viewId);
687 * Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have
688 * a configuration step, this allows the proper animations to run after other transitions.
690 private long completeAdd(PendingAddArguments args) {
691 long screenId = args.screenId;
692 if (args.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
693 // When the screen id represents an actual screen (as opposed to a rank) we make sure
694 // that the drop page actually exists.
695 screenId = ensurePendingDropLayoutExists(args.screenId);
698 switch (args.requestCode) {
699 case REQUEST_CREATE_SHORTCUT:
700 completeAddShortcut(args.intent, args.container, screenId, args.cellX,
703 case REQUEST_CREATE_APPWIDGET:
704 completeAddAppWidget(args.appWidgetId, args.container, screenId, null, null);
706 case REQUEST_RECONFIGURE_APPWIDGET:
707 completeRestoreAppWidget(args.appWidgetId);
710 // Before adding this resetAddInfo(), after a shortcut was added to a workspace screen,
711 // if you turned the screen off and then back while in All Apps, Launcher would not
712 // return to the workspace. Clearing mAddInfo.container here fixes this issue
717 private void handleActivityResult(
718 final int requestCode, final int resultCode, final Intent data) {
719 // Reset the startActivity waiting flag
720 setWaitingForResult(false);
721 final int pendingAddWidgetId = mPendingAddWidgetId;
722 mPendingAddWidgetId = -1;
724 Runnable exitSpringLoaded = new Runnable() {
727 exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED),
728 EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
732 if (requestCode == REQUEST_BIND_APPWIDGET) {
733 // This is called only if the user did not previously have permissions to bind widgets
734 final int appWidgetId = data != null ?
735 data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
736 if (resultCode == RESULT_CANCELED) {
737 completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
738 mWorkspace.removeExtraEmptyScreenDelayed(true, exitSpringLoaded,
739 ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
740 } else if (resultCode == RESULT_OK) {
741 addAppWidgetImpl(appWidgetId, mPendingAddInfo, null,
742 mPendingAddWidgetInfo, ON_ACTIVITY_RESULT_ANIMATION_DELAY);
744 // When the user has granted permission to bind widgets, we should check to see if
745 // we can inflate the default search bar widget.
749 } else if (requestCode == REQUEST_PICK_WALLPAPER) {
750 if (resultCode == RESULT_OK && mWorkspace.isInOverviewMode()) {
751 showWorkspace(false);
756 boolean isWidgetDrop = (requestCode == REQUEST_PICK_APPWIDGET ||
757 requestCode == REQUEST_CREATE_APPWIDGET);
759 final boolean workspaceLocked = isWorkspaceLocked();
760 // We have special handling for widgets
762 final int appWidgetId;
763 int widgetId = data != null ? data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1)
766 appWidgetId = pendingAddWidgetId;
768 appWidgetId = widgetId;
772 if (appWidgetId < 0 || resultCode == RESULT_CANCELED) {
773 Log.e(TAG, "Error: appWidgetId (EXTRA_APPWIDGET_ID) was not " +
774 "returned from the widget configuration activity.");
775 result = RESULT_CANCELED;
776 completeTwoStageWidgetDrop(result, appWidgetId);
777 final Runnable onComplete = new Runnable() {
780 exitSpringLoadedDragModeDelayed(false, 0, null);
783 if (workspaceLocked) {
784 // No need to remove the empty screen if we're mid-binding, as the
785 // the bind will not add the empty screen.
786 mWorkspace.postDelayed(onComplete, ON_ACTIVITY_RESULT_ANIMATION_DELAY);
788 mWorkspace.removeExtraEmptyScreenDelayed(true, onComplete,
789 ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
792 if (!workspaceLocked) {
793 if (mPendingAddInfo.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
794 // When the screen id represents an actual screen (as opposed to a rank)
795 // we make sure that the drop page actually exists.
796 mPendingAddInfo.screenId =
797 ensurePendingDropLayoutExists(mPendingAddInfo.screenId);
799 final CellLayout dropLayout = mWorkspace.getScreenWithId(mPendingAddInfo.screenId);
801 dropLayout.setDropPending(true);
802 final Runnable onComplete = new Runnable() {
805 completeTwoStageWidgetDrop(resultCode, appWidgetId);
806 dropLayout.setDropPending(false);
809 mWorkspace.removeExtraEmptyScreenDelayed(true, onComplete,
810 ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
812 PendingAddArguments args = preparePendingAddArgs(requestCode, data, appWidgetId,
814 sPendingAddItem = args;
820 if (requestCode == REQUEST_RECONFIGURE_APPWIDGET) {
821 if (resultCode == RESULT_OK) {
822 // Update the widget view.
823 PendingAddArguments args = preparePendingAddArgs(requestCode, data,
824 pendingAddWidgetId, mPendingAddInfo);
825 if (workspaceLocked) {
826 sPendingAddItem = args;
831 // Leave the widget in the pending state if the user canceled the configure.
835 // The pattern used here is that a user PICKs a specific application,
836 // which, depending on the target, might need to CREATE the actual target.
838 // For example, the user would PICK_SHORTCUT for "Music playlist", and we
839 // launch over to the Music app to actually CREATE_SHORTCUT.
840 if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID) {
841 final PendingAddArguments args = preparePendingAddArgs(requestCode, data, -1,
843 if (isWorkspaceLocked()) {
844 sPendingAddItem = args;
847 mWorkspace.removeExtraEmptyScreenDelayed(true, exitSpringLoaded,
848 ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
850 } else if (resultCode == RESULT_CANCELED) {
851 mWorkspace.removeExtraEmptyScreenDelayed(true, exitSpringLoaded,
852 ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
854 mDragLayer.clearAnimatedView();
859 protected void onActivityResult(
860 final int requestCode, final int resultCode, final Intent data) {
861 handleActivityResult(requestCode, resultCode, data);
862 if (mLauncherCallbacks != null) {
863 mLauncherCallbacks.onActivityResult(requestCode, resultCode, data);
867 /** @Override for MNC */
868 public void onRequestPermissionsResult(int requestCode, String[] permissions,
869 int[] grantResults) {
870 if (mLauncherCallbacks != null) {
871 mLauncherCallbacks.onRequestPermissionsResult(requestCode, permissions,
876 private PendingAddArguments preparePendingAddArgs(int requestCode, Intent data, int
877 appWidgetId, ItemInfo info) {
878 PendingAddArguments args = new PendingAddArguments();
879 args.requestCode = requestCode;
881 args.container = info.container;
882 args.screenId = info.screenId;
883 args.cellX = info.cellX;
884 args.cellY = info.cellY;
885 args.appWidgetId = appWidgetId;
890 * Check to see if a given screen id exists. If not, create it at the end, return the new id.
892 * @param screenId the screen id to check
893 * @return the new screen, or screenId if it exists
895 private long ensurePendingDropLayoutExists(long screenId) {
896 CellLayout dropLayout =
897 (CellLayout) mWorkspace.getScreenWithId(screenId);
898 if (dropLayout == null) {
899 // it's possible that the add screen was removed because it was
900 // empty and a re-bind occurred
901 mWorkspace.addExtraEmptyScreen();
902 return mWorkspace.commitExtraEmptyScreen();
908 @Thunk void completeTwoStageWidgetDrop(final int resultCode, final int appWidgetId) {
909 CellLayout cellLayout =
910 (CellLayout) mWorkspace.getScreenWithId(mPendingAddInfo.screenId);
911 Runnable onCompleteRunnable = null;
912 int animationType = 0;
914 AppWidgetHostView boundWidget = null;
915 if (resultCode == RESULT_OK) {
916 animationType = Workspace.COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION;
917 final AppWidgetHostView layout = mAppWidgetHost.createView(this, appWidgetId,
918 mPendingAddWidgetInfo);
919 boundWidget = layout;
920 onCompleteRunnable = new Runnable() {
923 completeAddAppWidget(appWidgetId, mPendingAddInfo.container,
924 mPendingAddInfo.screenId, layout, null);
925 exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED),
926 EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
929 } else if (resultCode == RESULT_CANCELED) {
930 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
931 animationType = Workspace.CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION;
933 if (mDragLayer.getAnimatedView() != null) {
934 mWorkspace.animateWidgetDrop(mPendingAddInfo, cellLayout,
935 (DragView) mDragLayer.getAnimatedView(), onCompleteRunnable,
936 animationType, boundWidget, true);
937 } else if (onCompleteRunnable != null) {
938 // The animated view may be null in the case of a rotation during widget configuration
939 onCompleteRunnable.run();
944 protected void onStop() {
946 FirstFrameAnimatorHelper.setIsVisible(false);
948 if (mLauncherCallbacks != null) {
949 mLauncherCallbacks.onStop();
954 protected void onStart() {
956 FirstFrameAnimatorHelper.setIsVisible(true);
958 if (mLauncherCallbacks != null) {
959 mLauncherCallbacks.onStart();
964 protected void onResume() {
966 if (DEBUG_RESUME_TIME) {
967 startTime = System.currentTimeMillis();
968 Log.v(TAG, "Launcher.onResume()");
971 if (mLauncherCallbacks != null) {
972 mLauncherCallbacks.preOnResume();
977 // Restore the previous launcher state
978 if (mOnResumeState == State.WORKSPACE) {
979 showWorkspace(false);
980 } else if (mOnResumeState == State.APPS) {
981 boolean launchedFromApp = (mWaitingForResume != null);
982 // Don't update the predicted apps if the user is returning to launcher in the apps
983 // view after launching an app, as they may be depending on the UI to be static to
984 // switch to another app, otherwise, if it was
985 showAppsView(false /* animated */, false /* resetListToTop */,
986 !launchedFromApp /* updatePredictedApps */, false /* focusSearchBar */);
987 } else if (mOnResumeState == State.WIDGETS) {
988 showWidgetsView(false, false);
990 mOnResumeState = State.NONE;
992 // Background was set to gradient in onPause(), restore to transparent if in all apps.
993 setWorkspaceBackground(mState == State.WORKSPACE ? WORKSPACE_BACKGROUND_GRADIENT
994 : WORKSPACE_BACKGROUND_TRANSPARENT);
997 if (mRestoring || mOnResumeNeedsLoad) {
998 setWorkspaceLoading(true);
999 mModel.startLoader(PagedView.INVALID_RESTORE_PAGE);
1001 mOnResumeNeedsLoad = false;
1003 if (mBindOnResumeCallbacks.size() > 0) {
1004 // We might have postponed some bind calls until onResume (see waitUntilResume) --
1005 // execute them here
1006 long startTimeCallbacks = 0;
1007 if (DEBUG_RESUME_TIME) {
1008 startTimeCallbacks = System.currentTimeMillis();
1011 for (int i = 0; i < mBindOnResumeCallbacks.size(); i++) {
1012 mBindOnResumeCallbacks.get(i).run();
1014 mBindOnResumeCallbacks.clear();
1015 if (DEBUG_RESUME_TIME) {
1016 Log.d(TAG, "Time spent processing callbacks in onResume: " +
1017 (System.currentTimeMillis() - startTimeCallbacks));
1020 if (mOnResumeCallbacks.size() > 0) {
1021 for (int i = 0; i < mOnResumeCallbacks.size(); i++) {
1022 mOnResumeCallbacks.get(i).run();
1024 mOnResumeCallbacks.clear();
1027 // Reset the pressed state of icons that were locked in the press state while activities
1029 if (mWaitingForResume != null) {
1030 // Resets the previous workspace icon press state
1031 mWaitingForResume.setStayPressed(false);
1034 // It is possible that widgets can receive updates while launcher is not in the foreground.
1035 // Consequently, the widgets will be inflated in the orientation of the foreground activity
1036 // (framework issue). On resuming, we ensure that any widgets are inflated for the current
1038 getWorkspace().reinflateWidgetsIfNecessary();
1039 reinflateQSBIfNecessary();
1041 if (DEBUG_RESUME_TIME) {
1042 Log.d(TAG, "Time spent in onResume: " + (System.currentTimeMillis() - startTime));
1045 if (mWorkspace.getCustomContentCallbacks() != null) {
1046 // If we are resuming and the custom content is the current page, we call onShow().
1047 // It is also poassible that onShow will instead be called slightly after first layout
1048 // if PagedView#setRestorePage was set to the custom content page in onCreate().
1049 if (mWorkspace.isOnOrMovingToCustomContent()) {
1050 mWorkspace.getCustomContentCallbacks().onShow(true);
1053 updateInteraction(Workspace.State.NORMAL, mWorkspace.getState());
1054 mWorkspace.onResume();
1056 if (!isWorkspaceLoading()) {
1057 // Process any items that were added while Launcher was away.
1058 InstallShortcutReceiver.disableAndFlushInstallQueue(this);
1061 if (mLauncherCallbacks != null) {
1062 mLauncherCallbacks.onResume();
1067 protected void onPause() {
1068 // Ensure that items added to Launcher are queued until Launcher returns
1069 InstallShortcutReceiver.enableInstallQueue();
1073 mDragController.cancelDrag();
1074 mDragController.resetLastGestureUpTime();
1076 // We call onHide() aggressively. The custom content callbacks should be able to
1077 // debounce excess onHide calls.
1078 if (mWorkspace.getCustomContentCallbacks() != null) {
1079 mWorkspace.getCustomContentCallbacks().onHide();
1082 if (mLauncherCallbacks != null) {
1083 mLauncherCallbacks.onPause();
1087 public interface CustomContentCallbacks {
1088 // Custom content is completely shown. {@code fromResume} indicates whether this was caused
1089 // by a onResume or by scrolling otherwise.
1090 public void onShow(boolean fromResume);
1092 // Custom content is completely hidden
1093 public void onHide();
1095 // Custom content scroll progress changed. From 0 (not showing) to 1 (fully showing).
1096 public void onScrollProgressChanged(float progress);
1098 // Indicates whether the user is allowed to scroll away from the custom content.
1099 boolean isScrollingAllowed();
1102 public interface LauncherOverlay {
1105 * Touch interaction leading to overscroll has begun
1107 public void onScrollInteractionBegin();
1110 * Touch interaction related to overscroll has ended
1112 public void onScrollInteractionEnd();
1115 * Scroll progress, between 0 and 100, when the user scrolls beyond the leftmost
1116 * screen (or in the case of RTL, the rightmost screen).
1118 public void onScrollChange(int progress, boolean rtl);
1121 * Screen has stopped scrolling
1123 public void onScrollSettled();
1126 * This method can be called by the Launcher in order to force the LauncherOverlay
1127 * to exit fully immersive mode.
1129 public void forceExitFullImmersion();
1132 public interface LauncherSearchCallbacks {
1134 * Called when the search overlay is shown.
1136 public void onSearchOverlayOpened();
1139 * Called when the search overlay is dismissed.
1141 public void onSearchOverlayClosed();
1144 public interface LauncherOverlayCallbacks {
1146 * This method indicates whether a call to {@link #enterFullImmersion()} will succeed,
1147 * however it doesn't modify any state within the launcher.
1149 public boolean canEnterFullImmersion();
1152 * Should be called to tell Launcher that the LauncherOverlay will take over interaction,
1153 * eg. by occupying the full screen and handling all touch events.
1155 * @return true if Launcher allows the LauncherOverlay to become fully immersive. In this
1156 * case, Launcher will modify any necessary state and assumes the overlay is
1157 * handling all interaction. If false, the LauncherOverlay should cancel any
1160 public boolean enterFullImmersion();
1163 * Must be called when exiting fully immersive mode. Indicates to Launcher that it has
1164 * full control over UI and state.
1166 public void exitFullImmersion();
1169 class LauncherOverlayCallbacksImpl implements LauncherOverlayCallbacks {
1172 public boolean canEnterFullImmersion() {
1173 return mState == State.WORKSPACE;
1177 public boolean enterFullImmersion() {
1178 if (mState == State.WORKSPACE) {
1179 // When fully immersed, disregard any touches which fall through.
1180 mDragLayer.setBlockTouch(true);
1187 public void exitFullImmersion() {
1188 mDragLayer.setBlockTouch(false);
1192 protected boolean hasSettings() {
1193 if (mLauncherCallbacks != null) {
1194 return mLauncherCallbacks.hasSettings();
1196 // On devices with a locked orientation, we will at least have the allow rotation
1198 return !Utilities.isRotationAllowedForDevice(this);
1202 public void addToCustomContentPage(View customContent,
1203 CustomContentCallbacks callbacks, String description) {
1204 mWorkspace.addToCustomContentPage(customContent, callbacks, description);
1207 // The custom content needs to offset its content to account for the QSB
1208 public int getTopOffsetForCustomContent() {
1209 return mWorkspace.getPaddingTop();
1213 public Object onRetainNonConfigurationInstance() {
1214 // Flag the loader to stop early before switching
1215 if (mModel.isCurrentCallbacks(this)) {
1216 mModel.stopLoader();
1218 //TODO(hyunyoungs): stop the widgets loader when there is a rotation.
1220 return Boolean.TRUE;
1223 // We can't hide the IME if it was forced open. So don't bother
1225 public void onWindowFocusChanged(boolean hasFocus) {
1226 super.onWindowFocusChanged(hasFocus);
1227 mHasFocus = hasFocus;
1229 if (mLauncherCallbacks != null) {
1230 mLauncherCallbacks.onWindowFocusChanged(hasFocus);
1234 private boolean acceptFilter() {
1235 final InputMethodManager inputManager = (InputMethodManager)
1236 getSystemService(Context.INPUT_METHOD_SERVICE);
1237 return !inputManager.isFullscreenMode();
1241 public boolean onKeyDown(int keyCode, KeyEvent event) {
1242 final int uniChar = event.getUnicodeChar();
1243 final boolean handled = super.onKeyDown(keyCode, event);
1244 final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar);
1245 if (!handled && acceptFilter() && isKeyNotWhitespace) {
1246 boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
1248 if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
1249 // something usable has been typed - start a search
1250 // the typed text will be retrieved and cleared by
1251 // showSearchDialog()
1252 // If there are multiple keystrokes before the search dialog takes focus,
1253 // onSearchRequested() will be called for every keystroke,
1254 // but it is idempotent, so it's fine.
1255 return onSearchRequested();
1259 // Eat the long press event so the keyboard doesn't come up.
1260 if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
1267 private String getTypedText() {
1268 return mDefaultKeySsb.toString();
1271 private void clearTypedText() {
1272 mDefaultKeySsb.clear();
1273 mDefaultKeySsb.clearSpans();
1274 Selection.setSelection(mDefaultKeySsb, 0);
1278 * Given the integer (ordinal) value of a State enum instance, convert it to a variable of type
1281 private static State intToState(int stateOrdinal) {
1282 State state = State.WORKSPACE;
1283 final State[] stateValues = State.values();
1284 for (int i = 0; i < stateValues.length; i++) {
1285 if (stateValues[i].ordinal() == stateOrdinal) {
1286 state = stateValues[i];
1294 * Restores the previous state, if it exists.
1296 * @param savedState The previous state.
1298 @SuppressWarnings("unchecked")
1299 private void restoreState(Bundle savedState) {
1300 if (savedState == null) {
1304 State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
1305 if (state == State.APPS || state == State.WIDGETS) {
1306 mOnResumeState = state;
1309 int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN,
1310 PagedView.INVALID_RESTORE_PAGE);
1311 if (currentScreen != PagedView.INVALID_RESTORE_PAGE) {
1312 mWorkspace.setRestorePage(currentScreen);
1315 final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
1316 final long pendingAddScreen = savedState.getLong(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
1318 if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
1319 mPendingAddInfo.container = pendingAddContainer;
1320 mPendingAddInfo.screenId = pendingAddScreen;
1321 mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
1322 mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
1323 mPendingAddInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
1324 mPendingAddInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
1325 AppWidgetProviderInfo info = savedState.getParcelable(
1326 RUNTIME_STATE_PENDING_ADD_WIDGET_INFO);
1327 mPendingAddWidgetInfo = info == null ?
1328 null : LauncherAppWidgetProviderInfo.fromProviderInfo(this, info);
1330 mPendingAddWidgetId = savedState.getInt(RUNTIME_STATE_PENDING_ADD_WIDGET_ID);
1331 setWaitingForResult(true);
1335 mItemIdToViewId = (HashMap<Integer, Integer>)
1336 savedState.getSerializable(RUNTIME_STATE_VIEW_IDS);
1340 * Finds all the views we need and configure them properly.
1342 private void setupViews() {
1343 final DragController dragController = mDragController;
1345 mLauncherView = findViewById(R.id.launcher);
1346 mFocusHandler = (FocusIndicatorView) findViewById(R.id.focus_indicator);
1347 mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
1348 mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
1349 mWorkspace.setPageSwitchListener(this);
1350 mPageIndicators = mDragLayer.findViewById(R.id.page_indicator);
1352 mLauncherView.setSystemUiVisibility(
1353 View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
1354 mWorkspaceBackgroundDrawable = getResources().getDrawable(R.drawable.workspace_bg);
1356 // Setup the drag layer
1357 mDragLayer.setup(this, dragController);
1359 // Setup the hotseat
1360 mHotseat = (Hotseat) findViewById(R.id.hotseat);
1361 if (mHotseat != null) {
1362 mHotseat.setOnLongClickListener(this);
1365 mOverviewPanel = (ViewGroup) findViewById(R.id.overview_panel);
1366 mWidgetsButton = findViewById(R.id.widget_button);
1367 mWidgetsButton.setOnClickListener(new OnClickListener() {
1369 public void onClick(View arg0) {
1370 if (!mWorkspace.isSwitchingState()) {
1371 onClickAddWidgetButton(arg0);
1375 mWidgetsButton.setOnTouchListener(getHapticFeedbackTouchListener());
1377 View wallpaperButton = findViewById(R.id.wallpaper_button);
1378 wallpaperButton.setOnClickListener(new OnClickListener() {
1380 public void onClick(View arg0) {
1381 if (!mWorkspace.isSwitchingState()) {
1382 onClickWallpaperPicker(arg0);
1386 wallpaperButton.setOnTouchListener(getHapticFeedbackTouchListener());
1388 View settingsButton = findViewById(R.id.settings_button);
1389 if (hasSettings()) {
1390 settingsButton.setOnClickListener(new OnClickListener() {
1392 public void onClick(View arg0) {
1393 if (!mWorkspace.isSwitchingState()) {
1394 onClickSettingsButton(arg0);
1398 settingsButton.setOnTouchListener(getHapticFeedbackTouchListener());
1400 settingsButton.setVisibility(View.GONE);
1403 mOverviewPanel.setAlpha(0f);
1405 // Setup the workspace
1406 mWorkspace.setHapticFeedbackEnabled(false);
1407 mWorkspace.setOnLongClickListener(this);
1408 mWorkspace.setup(dragController);
1409 dragController.addDragListener(mWorkspace);
1411 // Get the search/delete bar
1412 mSearchDropTargetBar = (SearchDropTargetBar)
1413 mDragLayer.findViewById(R.id.search_drop_target_bar);
1415 // Setup Apps and Widgets
1416 mAppsView = (AllAppsContainerView) findViewById(R.id.apps_view);
1417 mWidgetsView = (WidgetsContainerView) findViewById(R.id.widgets_view);
1418 if (mLauncherCallbacks != null && mLauncherCallbacks.getAllAppsSearchBarController() != null) {
1419 mAppsView.setSearchBarController(mLauncherCallbacks.getAllAppsSearchBarController());
1421 mAppsView.setSearchBarController(mAppsView.newDefaultAppSearchController());
1424 // Setup the drag controller (drop targets have to be added in reverse order in priority)
1425 dragController.setDragScoller(mWorkspace);
1426 dragController.setScrollView(mDragLayer);
1427 dragController.setMoveTarget(mWorkspace);
1428 dragController.addDropTarget(mWorkspace);
1429 if (mSearchDropTargetBar != null) {
1430 mSearchDropTargetBar.setup(this, dragController);
1431 mSearchDropTargetBar.setQsbSearchBar(getOrCreateQsbBar());
1434 if (getResources().getBoolean(R.bool.debug_memory_enabled)) {
1435 Log.v(TAG, "adding WeightWatcher");
1436 mWeightWatcher = new WeightWatcher(this);
1437 mWeightWatcher.setAlpha(0.5f);
1438 ((FrameLayout) mLauncherView).addView(mWeightWatcher,
1439 new FrameLayout.LayoutParams(
1440 FrameLayout.LayoutParams.MATCH_PARENT,
1441 FrameLayout.LayoutParams.WRAP_CONTENT,
1445 boolean show = shouldShowWeightWatcher();
1446 mWeightWatcher.setVisibility(show ? View.VISIBLE : View.GONE);
1451 * Sets the all apps button. This method is called from {@link Hotseat}.
1453 public void setAllAppsButton(View allAppsButton) {
1454 mAllAppsButton = allAppsButton;
1457 public View getAllAppsButton() {
1458 return mAllAppsButton;
1461 public View getWidgetsButton() {
1462 return mWidgetsButton;
1466 * Creates a view representing a shortcut.
1468 * @param info The data structure describing the shortcut.
1470 View createShortcut(ShortcutInfo info) {
1471 return createShortcut((ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info);
1475 * Creates a view representing a shortcut inflated from the specified resource.
1477 * @param parent The group the shortcut belongs to.
1478 * @param info The data structure describing the shortcut.
1480 * @return A View inflated from layoutResId.
1482 public View createShortcut(ViewGroup parent, ShortcutInfo info) {
1483 BubbleTextView favorite = (BubbleTextView) mInflater.inflate(R.layout.app_icon,
1485 favorite.applyFromShortcutInfo(info, mIconCache);
1486 favorite.setCompoundDrawablePadding(mDeviceProfile.iconDrawablePaddingPx);
1487 favorite.setOnClickListener(this);
1488 favorite.setOnFocusChangeListener(mFocusHandler);
1493 * Add a shortcut to the workspace.
1495 * @param data The intent describing the shortcut.
1497 private void completeAddShortcut(Intent data, long container, long screenId, int cellX,
1499 int[] cellXY = mTmpAddItemCellCoordinates;
1500 int[] touchXY = mPendingAddInfo.dropPos;
1501 CellLayout layout = getCellLayout(container, screenId);
1503 ShortcutInfo info = InstallShortcutReceiver.fromShortcutIntent(this, data);
1507 final View view = createShortcut(info);
1509 boolean foundCellSpan = false;
1510 // First we check if we already know the exact location where we want to add this item.
1511 if (cellX >= 0 && cellY >= 0) {
1514 foundCellSpan = true;
1516 // If appropriate, either create a folder or add to an existing folder
1517 if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0,
1521 DragObject dragObject = new DragObject();
1522 dragObject.dragInfo = info;
1523 if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject,
1527 } else if (touchXY != null) {
1528 // when dragging and dropping, just find the closest free spot
1529 int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY);
1530 foundCellSpan = (result != null);
1532 foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
1535 if (!foundCellSpan) {
1536 showOutOfSpaceMessage(isHotseatLayout(layout));
1540 LauncherModel.addItemToDatabase(this, info, container, screenId, cellXY[0], cellXY[1]);
1543 mWorkspace.addInScreen(view, container, screenId, cellXY[0], cellXY[1], 1, 1,
1544 isWorkspaceLocked());
1549 * Add a widget to the workspace.
1551 * @param appWidgetId The app widget id
1553 @Thunk void completeAddAppWidget(int appWidgetId, long container, long screenId,
1554 AppWidgetHostView hostView, LauncherAppWidgetProviderInfo appWidgetInfo) {
1556 ItemInfo info = mPendingAddInfo;
1557 if (appWidgetInfo == null) {
1558 appWidgetInfo = LauncherAppWidgetProviderInfo.fromProviderInfo(this,
1559 mAppWidgetManager.getAppWidgetInfo(appWidgetId));
1562 if (appWidgetInfo.isCustomWidget) {
1563 appWidgetId = LauncherAppWidgetInfo.CUSTOM_WIDGET_ID;
1566 LauncherAppWidgetInfo launcherInfo;
1567 launcherInfo = new LauncherAppWidgetInfo(appWidgetId, appWidgetInfo.provider);
1568 launcherInfo.spanX = info.spanX;
1569 launcherInfo.spanY = info.spanY;
1570 launcherInfo.minSpanX = info.minSpanX;
1571 launcherInfo.minSpanY = info.minSpanY;
1572 launcherInfo.user = mAppWidgetManager.getUser(appWidgetInfo);
1574 LauncherModel.addItemToDatabase(this, launcherInfo,
1575 container, screenId, info.cellX, info.cellY);
1578 if (hostView == null) {
1579 // Perform actual inflation because we're live
1580 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId,
1583 // The AppWidgetHostView has already been inflated and instantiated
1584 launcherInfo.hostView = hostView;
1586 launcherInfo.hostView.setTag(launcherInfo);
1587 launcherInfo.hostView.setVisibility(View.VISIBLE);
1588 launcherInfo.notifyWidgetSizeChanged(this);
1590 mWorkspace.addInScreen(launcherInfo.hostView, container, screenId, info.cellX,
1591 info.cellY, launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
1593 addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
1598 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1600 public void onReceive(Context context, Intent intent) {
1601 final String action = intent.getAction();
1602 if (Intent.ACTION_SCREEN_OFF.equals(action)) {
1603 mUserPresent = false;
1604 mDragLayer.clearAllResizeFrames();
1605 updateAutoAdvanceState();
1607 // Reset AllApps to its initial state only if we are not in the middle of
1608 // processing a multi-step drop
1609 if (mAppsView != null && mWidgetsView != null &&
1610 mPendingAddInfo.container == ItemInfo.NO_ID) {
1611 showWorkspace(false);
1613 } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
1614 mUserPresent = true;
1615 updateAutoAdvanceState();
1616 } else if (ENABLE_DEBUG_INTENTS && DebugIntents.DELETE_DATABASE.equals(action)) {
1617 mModel.resetLoadedState(false, true);
1618 mModel.startLoader(PagedView.INVALID_RESTORE_PAGE,
1619 LauncherModel.LOADER_FLAG_CLEAR_WORKSPACE);
1620 } else if (ENABLE_DEBUG_INTENTS && DebugIntents.MIGRATE_DATABASE.equals(action)) {
1621 mModel.resetLoadedState(false, true);
1622 mModel.startLoader(PagedView.INVALID_RESTORE_PAGE,
1623 LauncherModel.LOADER_FLAG_CLEAR_WORKSPACE
1624 | LauncherModel.LOADER_FLAG_MIGRATE_SHORTCUTS);
1630 public void onAttachedToWindow() {
1631 super.onAttachedToWindow();
1633 // Listen for broadcasts related to user-presence
1634 final IntentFilter filter = new IntentFilter();
1635 filter.addAction(Intent.ACTION_SCREEN_OFF);
1636 filter.addAction(Intent.ACTION_USER_PRESENT);
1637 // For handling managed profiles
1638 if (ENABLE_DEBUG_INTENTS) {
1639 filter.addAction(DebugIntents.DELETE_DATABASE);
1640 filter.addAction(DebugIntents.MIGRATE_DATABASE);
1642 registerReceiver(mReceiver, filter);
1643 FirstFrameAnimatorHelper.initializeDrawListener(getWindow().getDecorView());
1644 setupTransparentSystemBarsForLollipop();
1650 * Sets up transparent navigation and status bars in Lollipop.
1651 * This method is a no-op for other platform versions.
1653 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
1654 private void setupTransparentSystemBarsForLollipop() {
1655 if (Utilities.ATLEAST_LOLLIPOP) {
1656 Window window = getWindow();
1657 window.getAttributes().systemUiVisibility |=
1658 (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
1659 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
1660 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
1661 window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
1662 | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1663 window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
1664 window.setStatusBarColor(Color.TRANSPARENT);
1665 window.setNavigationBarColor(Color.TRANSPARENT);
1670 public void onDetachedFromWindow() {
1671 super.onDetachedFromWindow();
1675 unregisterReceiver(mReceiver);
1678 updateAutoAdvanceState();
1681 public void onWindowVisibilityChanged(int visibility) {
1682 mVisible = visibility == View.VISIBLE;
1683 updateAutoAdvanceState();
1684 // The following code used to be in onResume, but it turns out onResume is called when
1685 // you're in All Apps and click home to go to the workspace. onWindowVisibilityChanged
1686 // is a more appropriate event to handle
1688 if (!mWorkspaceLoading) {
1689 final ViewTreeObserver observer = mWorkspace.getViewTreeObserver();
1690 // We want to let Launcher draw itself at least once before we force it to build
1691 // layers on all the workspace pages, so that transitioning to Launcher from other
1692 // apps is nice and speedy.
1693 observer.addOnDrawListener(new ViewTreeObserver.OnDrawListener() {
1694 private boolean mStarted = false;
1695 public void onDraw() {
1696 if (mStarted) return;
1698 // We delay the layer building a bit in order to give
1699 // other message processing a time to run. In particular
1700 // this avoids a delay in hiding the IME if it was
1701 // currently shown, because doing that may involve
1702 // some communication back with the app.
1703 mWorkspace.postDelayed(mBuildLayersRunnable, 500);
1704 final ViewTreeObserver.OnDrawListener listener = this;
1705 mWorkspace.post(new Runnable() {
1707 if (mWorkspace != null &&
1708 mWorkspace.getViewTreeObserver() != null) {
1709 mWorkspace.getViewTreeObserver().
1710 removeOnDrawListener(listener);
1722 @Thunk void sendAdvanceMessage(long delay) {
1723 mHandler.removeMessages(ADVANCE_MSG);
1724 Message msg = mHandler.obtainMessage(ADVANCE_MSG);
1725 mHandler.sendMessageDelayed(msg, delay);
1726 mAutoAdvanceSentTime = System.currentTimeMillis();
1729 @Thunk void updateAutoAdvanceState() {
1730 boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
1731 if (autoAdvanceRunning != mAutoAdvanceRunning) {
1732 mAutoAdvanceRunning = autoAdvanceRunning;
1733 if (autoAdvanceRunning) {
1734 long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
1735 sendAdvanceMessage(delay);
1737 if (!mWidgetsToAdvance.isEmpty()) {
1738 mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
1739 (System.currentTimeMillis() - mAutoAdvanceSentTime));
1741 mHandler.removeMessages(ADVANCE_MSG);
1742 mHandler.removeMessages(0); // Remove messages sent using postDelayed()
1747 @Thunk final Handler mHandler = new Handler(new Handler.Callback() {
1750 public boolean handleMessage(Message msg) {
1751 if (msg.what == ADVANCE_MSG) {
1753 for (View key: mWidgetsToAdvance.keySet()) {
1754 final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
1755 final int delay = mAdvanceStagger * i;
1756 if (v instanceof Advanceable) {
1757 mHandler.postDelayed(new Runnable() {
1759 ((Advanceable) v).advance();
1765 sendAdvanceMessage(mAdvanceInterval);
1771 void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
1772 if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
1773 View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
1774 if (v instanceof Advanceable) {
1775 mWidgetsToAdvance.put(hostView, appWidgetInfo);
1776 ((Advanceable) v).fyiWillBeAdvancedByHostKThx();
1777 updateAutoAdvanceState();
1781 void removeWidgetToAutoAdvance(View hostView) {
1782 if (mWidgetsToAdvance.containsKey(hostView)) {
1783 mWidgetsToAdvance.remove(hostView);
1784 updateAutoAdvanceState();
1788 public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
1789 removeWidgetToAutoAdvance(launcherInfo.hostView);
1790 launcherInfo.hostView = null;
1793 public void showOutOfSpaceMessage(boolean isHotseatLayout) {
1794 int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space);
1795 Toast.makeText(this, getString(strId), Toast.LENGTH_SHORT).show();
1798 public DragLayer getDragLayer() {
1802 public AllAppsContainerView getAppsView() {
1806 public WidgetsContainerView getWidgetsView() {
1807 return mWidgetsView;
1810 public Workspace getWorkspace() {
1814 public Hotseat getHotseat() {
1818 public ViewGroup getOverviewPanel() {
1819 return mOverviewPanel;
1822 public SearchDropTargetBar getSearchDropTargetBar() {
1823 return mSearchDropTargetBar;
1826 public LauncherAppWidgetHost getAppWidgetHost() {
1827 return mAppWidgetHost;
1830 public LauncherModel getModel() {
1834 protected SharedPreferences getSharedPrefs() {
1835 return mSharedPrefs;
1838 public DeviceProfile getDeviceProfile() {
1839 return mDeviceProfile;
1842 public void closeSystemDialogs() {
1843 getWindow().closeAllPanels();
1845 // Whatever we were doing is hereby canceled.
1846 setWaitingForResult(false);
1850 protected void onNewIntent(Intent intent) {
1852 if (DEBUG_RESUME_TIME) {
1853 startTime = System.currentTimeMillis();
1855 super.onNewIntent(intent);
1858 Folder openFolder = mWorkspace.getOpenFolder();
1859 boolean alreadyOnHome = mHasFocus && ((intent.getFlags() &
1860 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
1861 != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
1862 boolean isActionMain = Intent.ACTION_MAIN.equals(intent.getAction());
1864 // also will cancel mWaitingForResult.
1865 closeSystemDialogs();
1867 if (mWorkspace == null) {
1868 // Can be cases where mWorkspace is null, this prevents a NPE
1871 // In all these cases, only animate if we're already on home
1872 mWorkspace.exitWidgetResizeMode();
1875 exitSpringLoadedDragMode();
1877 // If we are already on home, then just animate back to the workspace,
1878 // otherwise, just wait until onResume to set the state back to Workspace
1879 if (alreadyOnHome) {
1880 showWorkspace(true);
1882 mOnResumeState = State.WORKSPACE;
1885 final View v = getWindow().peekDecorView();
1886 if (v != null && v.getWindowToken() != null) {
1887 InputMethodManager imm = (InputMethodManager)getSystemService(
1888 INPUT_METHOD_SERVICE);
1889 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
1892 // Reset the apps view
1893 if (!alreadyOnHome && mAppsView != null) {
1894 mAppsView.scrollToTop();
1897 // Reset the widgets view
1898 if (!alreadyOnHome && mWidgetsView != null) {
1899 mWidgetsView.scrollToTop();
1902 if (mLauncherCallbacks != null) {
1903 mLauncherCallbacks.onHomeIntent();
1907 if (mLauncherCallbacks != null) {
1908 mLauncherCallbacks.onNewIntent(intent);
1911 // Defer moving to the default screen until after we callback to the LauncherCallbacks
1912 // as slow logic in the callbacks eat into the time the scroller expects for the snapToPage
1915 boolean moveToDefaultScreen = mLauncherCallbacks != null ?
1916 mLauncherCallbacks.shouldMoveToDefaultScreenOnHomeIntent() : true;
1917 if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive() &&
1918 openFolder == null && moveToDefaultScreen) {
1919 mWorkspace.post(new Runnable() {
1922 mWorkspace.moveToDefaultScreen(true);
1928 if (DEBUG_RESUME_TIME) {
1929 Log.d(TAG, "Time spent in onNewIntent: " + (System.currentTimeMillis() - startTime));
1934 public void onRestoreInstanceState(Bundle state) {
1935 super.onRestoreInstanceState(state);
1936 for (int page: mSynchronouslyBoundPages) {
1937 mWorkspace.restoreInstanceStateForChild(page);
1942 protected void onSaveInstanceState(Bundle outState) {
1943 if (mWorkspace.getChildCount() > 0) {
1944 outState.putInt(RUNTIME_STATE_CURRENT_SCREEN,
1945 mWorkspace.getCurrentPageOffsetFromCustomContent());
1947 super.onSaveInstanceState(outState);
1949 outState.putInt(RUNTIME_STATE, mState.ordinal());
1950 // We close any open folder since it will not be re-opened, and we need to make sure
1951 // this state is reflected.
1954 if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screenId > -1 &&
1955 mWaitingForResult) {
1956 outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
1957 outState.putLong(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screenId);
1958 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
1959 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
1960 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, mPendingAddInfo.spanX);
1961 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, mPendingAddInfo.spanY);
1962 outState.putParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO, mPendingAddWidgetInfo);
1963 outState.putInt(RUNTIME_STATE_PENDING_ADD_WIDGET_ID, mPendingAddWidgetId);
1966 // Save the current widgets tray?
1968 outState.putSerializable(RUNTIME_STATE_VIEW_IDS, mItemIdToViewId);
1970 if (mLauncherCallbacks != null) {
1971 mLauncherCallbacks.onSaveInstanceState(outState);
1976 public void onDestroy() {
1979 // Remove all pending runnables
1980 mHandler.removeMessages(ADVANCE_MSG);
1981 mHandler.removeMessages(0);
1982 mWorkspace.removeCallbacks(mBuildLayersRunnable);
1984 // Stop callbacks from LauncherModel
1985 LauncherAppState app = (LauncherAppState.getInstance());
1987 // It's possible to receive onDestroy after a new Launcher activity has
1988 // been created. In this case, don't interfere with the new Launcher.
1989 if (mModel.isCurrentCallbacks(this)) {
1990 mModel.stopLoader();
1991 app.setLauncher(null);
1995 mAppWidgetHost.stopListening();
1996 } catch (NullPointerException ex) {
1997 Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
1999 mAppWidgetHost = null;
2001 mWidgetsToAdvance.clear();
2003 TextKeyListener.getInstance().release();
2005 unregisterReceiver(mCloseSystemDialogsReceiver);
2007 mDragLayer.clearAllResizeFrames();
2008 ((ViewGroup) mWorkspace.getParent()).removeAllViews();
2009 mWorkspace.removeAllWorkspaceScreens();
2011 mDragController = null;
2013 LauncherAnimUtils.onDestroyActivity();
2015 if (mLauncherCallbacks != null) {
2016 mLauncherCallbacks.onDestroy();
2020 public DragController getDragController() {
2021 return mDragController;
2025 public void startActivityForResult(Intent intent, int requestCode) {
2026 onStartForResult(requestCode);
2027 super.startActivityForResult(intent, requestCode);
2031 public void startIntentSenderForResult (IntentSender intent, int requestCode,
2032 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) {
2033 onStartForResult(requestCode);
2035 super.startIntentSenderForResult(intent, requestCode,
2036 fillInIntent, flagsMask, flagsValues, extraFlags, options);
2037 } catch (IntentSender.SendIntentException e) {
2038 throw new ActivityNotFoundException();
2042 private void onStartForResult(int requestCode) {
2043 if (requestCode >= 0) {
2044 setWaitingForResult(true);
2049 * Indicates that we want global search for this activity by setting the globalSearch
2050 * argument for {@link #startSearch} to true.
2053 public void startSearch(String initialQuery, boolean selectInitialQuery,
2054 Bundle appSearchData, boolean globalSearch) {
2056 if (initialQuery == null) {
2057 // Use any text typed in the launcher as the initial query
2058 initialQuery = getTypedText();
2060 if (appSearchData == null) {
2061 appSearchData = new Bundle();
2062 appSearchData.putString("source", "launcher-search");
2064 Rect sourceBounds = new Rect();
2065 if (mSearchDropTargetBar != null) {
2066 sourceBounds = mSearchDropTargetBar.getSearchBarBounds();
2069 boolean clearTextImmediately = startSearch(initialQuery, selectInitialQuery,
2070 appSearchData, sourceBounds);
2071 if (clearTextImmediately) {
2075 // We need to show the workspace after starting the search
2076 showWorkspace(true);
2080 * Start a text search.
2082 * @return {@code true} if the search will start immediately, so any further keypresses
2083 * will be handled directly by the search UI. {@code false} if {@link Launcher} should continue
2084 * to buffer keypresses.
2086 public boolean startSearch(String initialQuery,
2087 boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
2088 if (mLauncherCallbacks != null && mLauncherCallbacks.providesSearch()) {
2089 return mLauncherCallbacks.startSearch(initialQuery, selectInitialQuery, appSearchData,
2093 startGlobalSearch(initialQuery, selectInitialQuery,
2094 appSearchData, sourceBounds);
2099 * Starts the global search activity. This code is a copied from SearchManager
2101 private void startGlobalSearch(String initialQuery,
2102 boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
2103 final SearchManager searchManager =
2104 (SearchManager) getSystemService(Context.SEARCH_SERVICE);
2105 ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
2106 if (globalSearchActivity == null) {
2107 Log.w(TAG, "No global search activity found.");
2110 Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
2111 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2112 intent.setComponent(globalSearchActivity);
2113 // Make sure that we have a Bundle to put source in
2114 if (appSearchData == null) {
2115 appSearchData = new Bundle();
2117 appSearchData = new Bundle(appSearchData);
2119 // Set source to package name of app that starts global search if not set already.
2120 if (!appSearchData.containsKey("source")) {
2121 appSearchData.putString("source", getPackageName());
2123 intent.putExtra(SearchManager.APP_DATA, appSearchData);
2124 if (!TextUtils.isEmpty(initialQuery)) {
2125 intent.putExtra(SearchManager.QUERY, initialQuery);
2127 if (selectInitialQuery) {
2128 intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery);
2130 intent.setSourceBounds(sourceBounds);
2132 startActivity(intent);
2133 } catch (ActivityNotFoundException ex) {
2134 Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
2138 public void startSearchFromAllApps(View v, Intent searchIntent, String searchQuery) {
2139 if (mLauncherCallbacks != null && mLauncherCallbacks.startSearchFromAllApps(searchQuery)) {
2143 // If not handled, then just start the provided search intent
2144 startActivitySafely(v, searchIntent, null);
2147 public boolean isOnCustomContent() {
2148 return mWorkspace.isOnOrMovingToCustomContent();
2152 public boolean onPrepareOptionsMenu(Menu menu) {
2153 super.onPrepareOptionsMenu(menu);
2154 if (!isOnCustomContent()) {
2155 // Close any open folders
2157 // Stop resizing any widgets
2158 mWorkspace.exitWidgetResizeMode();
2159 if (!mWorkspace.isInOverviewMode()) {
2160 // Show the overview mode
2161 showOverviewMode(true);
2163 showWorkspace(true);
2166 if (mLauncherCallbacks != null) {
2167 return mLauncherCallbacks.onPrepareOptionsMenu(menu);
2174 public boolean onSearchRequested() {
2175 startSearch(null, false, null, true);
2176 // Use a custom animation for launching search
2180 public boolean isWorkspaceLocked() {
2181 return mWorkspaceLoading || mWaitingForResult;
2184 public boolean isWorkspaceLoading() {
2185 return mWorkspaceLoading;
2188 private void setWorkspaceLoading(boolean value) {
2189 boolean isLocked = isWorkspaceLocked();
2190 mWorkspaceLoading = value;
2191 if (isLocked != isWorkspaceLocked()) {
2192 onWorkspaceLockedChanged();
2196 private void setWaitingForResult(boolean value) {
2197 boolean isLocked = isWorkspaceLocked();
2198 mWaitingForResult = value;
2199 if (isLocked != isWorkspaceLocked()) {
2200 onWorkspaceLockedChanged();
2204 protected void onWorkspaceLockedChanged() {
2205 if (mLauncherCallbacks != null) {
2206 mLauncherCallbacks.onWorkspaceLockedChanged();
2210 private void resetAddInfo() {
2211 mPendingAddInfo.container = ItemInfo.NO_ID;
2212 mPendingAddInfo.screenId = -1;
2213 mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1;
2214 mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1;
2215 mPendingAddInfo.minSpanX = mPendingAddInfo.minSpanY = 1;
2216 mPendingAddInfo.dropPos = null;
2219 void addAppWidgetImpl(final int appWidgetId, final ItemInfo info, final
2220 AppWidgetHostView boundWidget, final LauncherAppWidgetProviderInfo appWidgetInfo) {
2221 addAppWidgetImpl(appWidgetId, info, boundWidget, appWidgetInfo, 0);
2224 void addAppWidgetImpl(final int appWidgetId, final ItemInfo info,
2225 final AppWidgetHostView boundWidget, final LauncherAppWidgetProviderInfo appWidgetInfo,
2227 if (appWidgetInfo.configure != null) {
2228 mPendingAddWidgetInfo = appWidgetInfo;
2229 mPendingAddWidgetId = appWidgetId;
2231 // Launch over to configure widget, if needed
2232 mAppWidgetManager.startConfigActivity(appWidgetInfo, appWidgetId, this,
2233 mAppWidgetHost, REQUEST_CREATE_APPWIDGET);
2236 // Otherwise just add it
2237 Runnable onComplete = new Runnable() {
2240 // Exit spring loaded mode if necessary after adding the widget
2241 exitSpringLoadedDragModeDelayed(true, EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT,
2245 completeAddAppWidget(appWidgetId, info.container, info.screenId, boundWidget,
2247 mWorkspace.removeExtraEmptyScreenDelayed(true, onComplete, delay, false);
2251 protected void moveToCustomContentScreen(boolean animate) {
2252 // Close any folders that may be open.
2254 mWorkspace.moveToCustomContentScreen(animate);
2257 public void addPendingItem(PendingAddItemInfo info, long container, long screenId,
2258 int[] cell, int spanX, int spanY) {
2259 switch (info.itemType) {
2260 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
2261 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2262 int span[] = new int[2];
2265 addAppWidgetFromDrop((PendingAddWidgetInfo) info,
2266 container, screenId, cell, span);
2268 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2269 processShortcutFromDrop(info.componentName, container, screenId, cell);
2272 throw new IllegalStateException("Unknown item type: " + info.itemType);
2277 * Process a shortcut drop.
2279 * @param componentName The name of the component
2280 * @param screenId The ID of the screen where it should be added
2281 * @param cell The cell it should be added to, optional
2283 private void processShortcutFromDrop(ComponentName componentName, long container, long screenId,
2286 mPendingAddInfo.container = container;
2287 mPendingAddInfo.screenId = screenId;
2288 mPendingAddInfo.dropPos = null;
2291 mPendingAddInfo.cellX = cell[0];
2292 mPendingAddInfo.cellY = cell[1];
2295 Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2296 createShortcutIntent.setComponent(componentName);
2297 Utilities.startActivityForResultSafely(this, createShortcutIntent, REQUEST_CREATE_SHORTCUT);
2301 * Process a widget drop.
2303 * @param info The PendingAppWidgetInfo of the widget being added.
2304 * @param screenId The ID of the screen where it should be added
2305 * @param cell The cell it should be added to, optional
2307 private void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, long screenId,
2308 int[] cell, int[] span) {
2310 mPendingAddInfo.container = info.container = container;
2311 mPendingAddInfo.screenId = info.screenId = screenId;
2312 mPendingAddInfo.dropPos = null;
2313 mPendingAddInfo.minSpanX = info.minSpanX;
2314 mPendingAddInfo.minSpanY = info.minSpanY;
2317 mPendingAddInfo.cellX = cell[0];
2318 mPendingAddInfo.cellY = cell[1];
2321 mPendingAddInfo.spanX = span[0];
2322 mPendingAddInfo.spanY = span[1];
2325 AppWidgetHostView hostView = info.boundWidget;
2327 if (hostView != null) {
2328 appWidgetId = hostView.getAppWidgetId();
2329 addAppWidgetImpl(appWidgetId, info, hostView, info.info);
2331 // Clear the boundWidget so that it doesn't get destroyed.
2332 info.boundWidget = null;
2334 // In this case, we either need to start an activity to get permission to bind
2335 // the widget, or we need to start an activity to configure the widget, or both.
2336 appWidgetId = getAppWidgetHost().allocateAppWidgetId();
2337 Bundle options = info.bindOptions;
2339 boolean success = mAppWidgetManager.bindAppWidgetIdIfAllowed(
2340 appWidgetId, info.info, options);
2342 addAppWidgetImpl(appWidgetId, info, null, info.info);
2344 mPendingAddWidgetInfo = info.info;
2345 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
2346 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
2347 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.componentName);
2348 mAppWidgetManager.getUser(mPendingAddWidgetInfo)
2349 .addToIntent(intent, AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE);
2350 // TODO: we need to make sure that this accounts for the options bundle.
2351 // intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, options);
2352 startActivityForResult(intent, REQUEST_BIND_APPWIDGET);
2357 FolderIcon addFolder(CellLayout layout, long container, final long screenId, int cellX,
2359 final FolderInfo folderInfo = new FolderInfo();
2360 folderInfo.title = getText(R.string.folder_name);
2363 LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screenId,
2365 sFolders.put(folderInfo.id, folderInfo);
2368 FolderIcon newFolder =
2369 FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache);
2370 mWorkspace.addInScreen(newFolder, container, screenId, cellX, cellY, 1, 1,
2371 isWorkspaceLocked());
2372 // Force measure the new folder icon
2373 CellLayout parent = mWorkspace.getParentCellLayoutForView(newFolder);
2374 parent.getShortcutsAndWidgets().measureChild(newFolder);
2378 void removeFolder(FolderInfo folder) {
2379 sFolders.remove(folder.id);
2383 public boolean dispatchKeyEvent(KeyEvent event) {
2384 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2385 switch (event.getKeyCode()) {
2386 case KeyEvent.KEYCODE_HOME:
2388 case KeyEvent.KEYCODE_VOLUME_DOWN:
2389 if (Utilities.isPropertyEnabled(DUMP_STATE_PROPERTY)) {
2395 } else if (event.getAction() == KeyEvent.ACTION_UP) {
2396 switch (event.getKeyCode()) {
2397 case KeyEvent.KEYCODE_HOME:
2402 return super.dispatchKeyEvent(event);
2406 public void onBackPressed() {
2407 if (mLauncherCallbacks != null && mLauncherCallbacks.handleBackPressed()) {
2411 if (mDragController.isDragging()) {
2412 mDragController.cancelDrag();
2416 if (isAppsViewVisible()) {
2417 showWorkspace(true);
2418 } else if (isWidgetsViewVisible()) {
2419 showOverviewMode(true);
2420 } else if (mWorkspace.isInOverviewMode()) {
2421 showWorkspace(true);
2422 } else if (mWorkspace.getOpenFolder() != null) {
2423 Folder openFolder = mWorkspace.getOpenFolder();
2424 if (openFolder.isEditingName()) {
2425 openFolder.dismissEditingName();
2430 mWorkspace.exitWidgetResizeMode();
2432 // Back button is a no-op here, but give at least some feedback for the button press
2433 mWorkspace.showOutlinesTemporarily();
2438 * Re-listen when widget host is reset.
2441 public void onAppWidgetHostReset() {
2442 if (mAppWidgetHost != null) {
2443 mAppWidgetHost.startListening();
2448 * Launches the intent referred by the clicked shortcut.
2450 * @param v The view representing the clicked shortcut.
2452 public void onClick(View v) {
2453 // Make sure that rogue clicks don't get through while allapps is launching, or after the
2454 // view has detached (it's possible for this to happen if the view is removed mid touch).
2455 if (v.getWindowToken() == null) {
2459 if (!mWorkspace.isFinishedSwitchingState()) {
2463 if (v instanceof Workspace) {
2464 if (mWorkspace.isInOverviewMode()) {
2465 showWorkspace(true);
2470 if (v instanceof CellLayout) {
2471 if (mWorkspace.isInOverviewMode()) {
2472 showWorkspace(mWorkspace.indexOfChild(v), true);
2476 Object tag = v.getTag();
2477 if (tag instanceof ShortcutInfo) {
2478 onClickAppShortcut(v);
2479 } else if (tag instanceof FolderInfo) {
2480 if (v instanceof FolderIcon) {
2481 onClickFolderIcon(v);
2483 } else if (v == mAllAppsButton) {
2484 onClickAllAppsButton(v);
2485 } else if (tag instanceof AppInfo) {
2486 startAppShortcutOrInfoActivity(v);
2487 } else if (tag instanceof LauncherAppWidgetInfo) {
2488 if (v instanceof PendingAppWidgetHostView) {
2489 onClickPendingWidget((PendingAppWidgetHostView) v);
2494 @SuppressLint("ClickableViewAccessibility")
2495 public boolean onTouch(View v, MotionEvent event) {
2500 * Event handler for the app widget view which has not fully restored.
2502 public void onClickPendingWidget(final PendingAppWidgetHostView v) {
2503 if (mIsSafeModeEnabled) {
2504 Toast.makeText(this, R.string.safemode_widget_error, Toast.LENGTH_SHORT).show();
2508 final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) v.getTag();
2509 if (v.isReadyForClickSetup()) {
2510 int widgetId = info.appWidgetId;
2511 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(widgetId);
2512 if (appWidgetInfo != null) {
2513 mPendingAddWidgetInfo = LauncherAppWidgetProviderInfo.fromProviderInfo(
2514 this, appWidgetInfo);
2515 mPendingAddInfo.copyFrom(info);
2516 mPendingAddWidgetId = widgetId;
2518 AppWidgetManagerCompat.getInstance(this).startConfigActivity(appWidgetInfo,
2519 info.appWidgetId, this, mAppWidgetHost, REQUEST_RECONFIGURE_APPWIDGET);
2521 } else if (info.installProgress < 0) {
2522 // The install has not been queued
2523 final String packageName = info.providerName.getPackageName();
2524 showBrokenAppInstallDialog(packageName,
2525 new DialogInterface.OnClickListener() {
2526 public void onClick(DialogInterface dialog, int id) {
2527 startActivitySafely(v, LauncherModel.getMarketIntent(packageName), info);
2531 // Download has started.
2532 final String packageName = info.providerName.getPackageName();
2533 startActivitySafely(v, LauncherModel.getMarketIntent(packageName), info);
2538 * Event handler for the "grid" button that appears on the home screen, which
2539 * enters all apps mode.
2541 * @param v The view that was clicked.
2543 protected void onClickAllAppsButton(View v) {
2544 if (LOGD) Log.d(TAG, "onClickAllAppsButton");
2545 if (!isAppsViewVisible()) {
2546 showAppsView(true /* animated */, false /* resetListToTop */,
2547 true /* updatePredictedApps */, false /* focusSearchBar */);
2549 if (mLauncherCallbacks != null) {
2550 mLauncherCallbacks.onClickAllAppsButton(v);
2555 protected void onLongClickAllAppsButton(View v) {
2556 if (LOGD) Log.d(TAG, "onLongClickAllAppsButton");
2557 if (!isAppsViewVisible()) {
2558 showAppsView(true /* animated */, false /* resetListToTop */,
2559 true /* updatePredictedApps */, true /* focusSearchBar */);
2563 private void showBrokenAppInstallDialog(final String packageName,
2564 DialogInterface.OnClickListener onSearchClickListener) {
2565 new AlertDialog.Builder(this)
2566 .setTitle(R.string.abandoned_promises_title)
2567 .setMessage(R.string.abandoned_promise_explanation)
2568 .setPositiveButton(R.string.abandoned_search, onSearchClickListener)
2569 .setNeutralButton(R.string.abandoned_clean_this,
2570 new DialogInterface.OnClickListener() {
2571 public void onClick(DialogInterface dialog, int id) {
2572 final UserHandleCompat user = UserHandleCompat.myUserHandle();
2573 mWorkspace.removeAbandonedPromise(packageName, user);
2581 * Event handler for an app shortcut click.
2583 * @param v The view that was clicked. Must be a tagged with a {@link ShortcutInfo}.
2585 protected void onClickAppShortcut(final View v) {
2586 if (LOGD) Log.d(TAG, "onClickAppShortcut");
2587 Object tag = v.getTag();
2588 if (!(tag instanceof ShortcutInfo)) {
2589 throw new IllegalArgumentException("Input must be a Shortcut");
2593 final ShortcutInfo shortcut = (ShortcutInfo) tag;
2595 if (shortcut.isDisabled != 0) {
2596 int error = R.string.activity_not_available;
2597 if ((shortcut.isDisabled & ShortcutInfo.FLAG_DISABLED_SAFEMODE) != 0) {
2598 error = R.string.safemode_shortcut_error;
2600 Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
2604 final Intent intent = shortcut.intent;
2606 // Check for special shortcuts
2607 if (intent.getComponent() != null) {
2608 final String shortcutClass = intent.getComponent().getClassName();
2610 if (shortcutClass.equals(MemoryDumpActivity.class.getName())) {
2611 MemoryDumpActivity.startDump(this);
2613 } else if (shortcutClass.equals(ToggleWeightWatcher.class.getName())) {
2614 toggleShowWeightWatcher();
2619 // Check for abandoned promise
2620 if ((v instanceof BubbleTextView)
2621 && shortcut.isPromise()
2622 && !shortcut.hasStatusFlag(ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE)) {
2623 showBrokenAppInstallDialog(
2624 shortcut.getTargetComponent().getPackageName(),
2625 new DialogInterface.OnClickListener() {
2626 public void onClick(DialogInterface dialog, int id) {
2627 startAppShortcutOrInfoActivity(v);
2634 startAppShortcutOrInfoActivity(v);
2636 if (mLauncherCallbacks != null) {
2637 mLauncherCallbacks.onClickAppShortcut(v);
2641 @Thunk void startAppShortcutOrInfoActivity(View v) {
2642 Object tag = v.getTag();
2643 final ShortcutInfo shortcut;
2644 final Intent intent;
2645 if (tag instanceof ShortcutInfo) {
2646 shortcut = (ShortcutInfo) tag;
2647 intent = shortcut.intent;
2648 int[] pos = new int[2];
2649 v.getLocationOnScreen(pos);
2650 intent.setSourceBounds(new Rect(pos[0], pos[1],
2651 pos[0] + v.getWidth(), pos[1] + v.getHeight()));
2653 } else if (tag instanceof AppInfo) {
2655 intent = ((AppInfo) tag).intent;
2657 throw new IllegalArgumentException("Input must be a Shortcut or AppInfo");
2660 boolean success = startActivitySafely(v, intent, tag);
2661 mStats.recordLaunch(v, intent, shortcut);
2663 if (success && v instanceof BubbleTextView) {
2664 mWaitingForResume = (BubbleTextView) v;
2665 mWaitingForResume.setStayPressed(true);
2670 * Event handler for a folder icon click.
2672 * @param v The view that was clicked. Must be an instance of {@link FolderIcon}.
2674 protected void onClickFolderIcon(View v) {
2675 if (LOGD) Log.d(TAG, "onClickFolder");
2676 if (!(v instanceof FolderIcon)){
2677 throw new IllegalArgumentException("Input must be a FolderIcon");
2680 // TODO(sunnygoyal): Re-evaluate this code.
2681 FolderIcon folderIcon = (FolderIcon) v;
2682 final FolderInfo info = folderIcon.getFolderInfo();
2683 Folder openFolder = mWorkspace.getFolderForTag(info);
2685 // If the folder info reports that the associated folder is open, then verify that
2686 // it is actually opened. There have been a few instances where this gets out of sync.
2687 if (info.opened && openFolder == null) {
2688 Log.d(TAG, "Folder info marked as open, but associated folder is not open. Screen: "
2689 + info.screenId + " (" + info.cellX + ", " + info.cellY + ")");
2690 info.opened = false;
2693 if (!info.opened && !folderIcon.getFolder().isDestroyed()) {
2694 // Close any open folder
2696 // Open the requested folder
2697 openFolder(folderIcon);
2699 // Find the open folder...
2701 if (openFolder != null) {
2702 folderScreen = mWorkspace.getPageForView(openFolder);
2704 closeFolder(openFolder);
2705 if (folderScreen != mWorkspace.getCurrentPage()) {
2706 // Close any folder open on the current screen
2708 // Pull the folder onto this screen
2709 openFolder(folderIcon);
2714 if (mLauncherCallbacks != null) {
2715 mLauncherCallbacks.onClickFolderIcon(v);
2720 * Event handler for the (Add) Widgets button that appears after a long press
2721 * on the home screen.
2723 protected void onClickAddWidgetButton(View view) {
2724 if (LOGD) Log.d(TAG, "onClickAddWidgetButton");
2725 if (mIsSafeModeEnabled) {
2726 Toast.makeText(this, R.string.safemode_widget_error, Toast.LENGTH_SHORT).show();
2728 showWidgetsView(true /* animated */, true /* resetPageToZero */);
2729 if (mLauncherCallbacks != null) {
2730 mLauncherCallbacks.onClickAddWidgetButton(view);
2736 * Event handler for the wallpaper picker button that appears after a long press
2737 * on the home screen.
2739 protected void onClickWallpaperPicker(View v) {
2740 if (LOGD) Log.d(TAG, "onClickWallpaperPicker");
2741 startActivityForResult(new Intent(Intent.ACTION_SET_WALLPAPER).setPackage(getPackageName()),
2742 REQUEST_PICK_WALLPAPER);
2744 if (mLauncherCallbacks != null) {
2745 mLauncherCallbacks.onClickWallpaperPicker(v);
2750 * Event handler for a click on the settings button that appears after a long press
2751 * on the home screen.
2753 protected void onClickSettingsButton(View v) {
2754 if (LOGD) Log.d(TAG, "onClickSettingsButton");
2755 if (mLauncherCallbacks != null) {
2756 mLauncherCallbacks.onClickSettingsButton(v);
2758 startActivity(new Intent(this, SettingsActivity.class));
2762 public View.OnTouchListener getHapticFeedbackTouchListener() {
2763 if (mHapticFeedbackTouchListener == null) {
2764 mHapticFeedbackTouchListener = new View.OnTouchListener() {
2765 @SuppressLint("ClickableViewAccessibility")
2767 public boolean onTouch(View v, MotionEvent event) {
2768 if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) {
2769 v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
2775 return mHapticFeedbackTouchListener;
2778 public void onDragStarted(View view) {
2779 if (isOnCustomContent()) {
2780 // Custom content screen doesn't participate in drag and drop. If on custom
2781 // content screen, move to default.
2782 moveWorkspaceToDefaultScreen();
2785 if (mLauncherCallbacks != null) {
2786 mLauncherCallbacks.onDragStarted(view);
2791 * Called when the user stops interacting with the launcher.
2792 * This implies that the user is now on the homescreen and is not doing housekeeping.
2794 protected void onInteractionEnd() {
2795 if (mLauncherCallbacks != null) {
2796 mLauncherCallbacks.onInteractionEnd();
2801 * Called when the user starts interacting with the launcher.
2802 * The possible interactions are:
2804 * - reorder an app shortcut, or a widget
2805 * - open the overview mode.
2806 * This is a good time to stop doing things that only make sense
2807 * when the user is on the homescreen and not doing housekeeping.
2809 protected void onInteractionBegin() {
2810 if (mLauncherCallbacks != null) {
2811 mLauncherCallbacks.onInteractionBegin();
2815 /** Updates the interaction state. */
2816 public void updateInteraction(Workspace.State fromState, Workspace.State toState) {
2817 // Only update the interacting state if we are transitioning to/from a view with an
2819 boolean fromStateWithOverlay = fromState != Workspace.State.NORMAL;
2820 boolean toStateWithOverlay = toState != Workspace.State.NORMAL;
2821 if (toStateWithOverlay) {
2822 onInteractionBegin();
2823 } else if (fromStateWithOverlay) {
2828 void startApplicationDetailsActivity(ComponentName componentName, UserHandleCompat user) {
2830 LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this);
2831 launcherApps.showAppDetailsForProfile(componentName, user);
2832 } catch (SecurityException e) {
2833 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2834 Log.e(TAG, "Launcher does not have permission to launch settings");
2835 } catch (ActivityNotFoundException e) {
2836 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2837 Log.e(TAG, "Unable to launch settings");
2841 // returns true if the activity was started
2842 boolean startApplicationUninstallActivity(ComponentName componentName, int flags,
2843 UserHandleCompat user) {
2844 if ((flags & AppInfo.DOWNLOADED_FLAG) == 0) {
2845 // System applications cannot be installed. For now, show a toast explaining that.
2846 // We may give them the option of disabling apps this way.
2847 int messageId = R.string.uninstall_system_app_text;
2848 Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
2851 String packageName = componentName.getPackageName();
2852 String className = componentName.getClassName();
2853 Intent intent = new Intent(
2854 Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
2855 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
2856 Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
2858 user.addToIntent(intent, Intent.EXTRA_USER);
2860 startActivity(intent);
2865 private boolean startActivity(View v, Intent intent, Object tag) {
2866 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2868 // Only launch using the new animation if the shortcut has not opted out (this is a
2869 // private contract between launcher and may be ignored in the future).
2870 boolean useLaunchAnimation = (v != null) &&
2871 !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
2872 LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this);
2873 UserManagerCompat userManager = UserManagerCompat.getInstance(this);
2875 UserHandleCompat user = null;
2876 if (intent.hasExtra(AppInfo.EXTRA_PROFILE)) {
2877 long serialNumber = intent.getLongExtra(AppInfo.EXTRA_PROFILE, -1);
2878 user = userManager.getUserForSerialNumber(serialNumber);
2881 Bundle optsBundle = null;
2882 if (useLaunchAnimation) {
2883 ActivityOptions opts = null;
2884 if (Utilities.ATLEAST_MARSHMALLOW) {
2885 int left = 0, top = 0;
2886 int width = v.getMeasuredWidth(), height = v.getMeasuredHeight();
2887 if (v instanceof TextView) {
2888 // Launch from center of icon, not entire view
2889 Drawable icon = Workspace.getTextViewIcon((TextView) v);
2891 Rect bounds = icon.getBounds();
2892 left = (width - bounds.width()) / 2;
2893 top = v.getPaddingTop();
2894 width = bounds.width();
2895 height = bounds.height();
2898 opts = ActivityOptions.makeClipRevealAnimation(v, left, top, width, height);
2899 } else if (!Utilities.ATLEAST_LOLLIPOP) {
2900 // Below L, we use a scale up animation
2901 opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
2902 v.getMeasuredWidth(), v.getMeasuredHeight());
2903 } else if (Utilities.ATLEAST_LOLLIPOP_MR1) {
2904 // On L devices, we use the device default slide-up transition.
2905 // On L MR1 devices, we a custom version of the slide-up transition which
2906 // doesn't have the delay present in the device default.
2907 opts = ActivityOptions.makeCustomAnimation(this,
2908 R.anim.task_open_enter, R.anim.no_anim);
2910 optsBundle = opts != null ? opts.toBundle() : null;
2913 if (user == null || user.equals(UserHandleCompat.myUserHandle())) {
2914 // Could be launching some bookkeeping activity
2915 startActivity(intent, optsBundle);
2917 // TODO Component can be null when shortcuts are supported for secondary user
2918 launcherApps.startActivityForProfile(intent.getComponent(), user,
2919 intent.getSourceBounds(), optsBundle);
2922 } catch (SecurityException e) {
2923 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2924 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
2925 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
2926 "or use the exported attribute for this activity. "
2927 + "tag="+ tag + " intent=" + intent, e);
2932 public boolean startActivitySafely(View v, Intent intent, Object tag) {
2933 boolean success = false;
2934 if (mIsSafeModeEnabled && !Utilities.isSystemApp(this, intent)) {
2935 Toast.makeText(this, R.string.safemode_shortcut_error, Toast.LENGTH_SHORT).show();
2939 success = startActivity(v, intent, tag);
2940 } catch (ActivityNotFoundException e) {
2941 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2942 Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
2948 * This method draws the FolderIcon to an ImageView and then adds and positions that ImageView
2949 * in the DragLayer in the exact absolute location of the original FolderIcon.
2951 private void copyFolderIconToImage(FolderIcon fi) {
2952 final int width = fi.getMeasuredWidth();
2953 final int height = fi.getMeasuredHeight();
2955 // Lazy load ImageView, Bitmap and Canvas
2956 if (mFolderIconImageView == null) {
2957 mFolderIconImageView = new ImageView(this);
2959 if (mFolderIconBitmap == null || mFolderIconBitmap.getWidth() != width ||
2960 mFolderIconBitmap.getHeight() != height) {
2961 mFolderIconBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
2962 mFolderIconCanvas = new Canvas(mFolderIconBitmap);
2965 DragLayer.LayoutParams lp;
2966 if (mFolderIconImageView.getLayoutParams() instanceof DragLayer.LayoutParams) {
2967 lp = (DragLayer.LayoutParams) mFolderIconImageView.getLayoutParams();
2969 lp = new DragLayer.LayoutParams(width, height);
2972 // The layout from which the folder is being opened may be scaled, adjust the starting
2973 // view size by this scale factor.
2974 float scale = mDragLayer.getDescendantRectRelativeToSelf(fi, mRectForFolderAnimation);
2975 lp.customPosition = true;
2976 lp.x = mRectForFolderAnimation.left;
2977 lp.y = mRectForFolderAnimation.top;
2978 lp.width = (int) (scale * width);
2979 lp.height = (int) (scale * height);
2981 mFolderIconCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
2982 fi.draw(mFolderIconCanvas);
2983 mFolderIconImageView.setImageBitmap(mFolderIconBitmap);
2984 if (fi.getFolder() != null) {
2985 mFolderIconImageView.setPivotX(fi.getFolder().getPivotXForIconAnimation());
2986 mFolderIconImageView.setPivotY(fi.getFolder().getPivotYForIconAnimation());
2988 // Just in case this image view is still in the drag layer from a previous animation,
2989 // we remove it and re-add it.
2990 if (mDragLayer.indexOfChild(mFolderIconImageView) != -1) {
2991 mDragLayer.removeView(mFolderIconImageView);
2993 mDragLayer.addView(mFolderIconImageView, lp);
2994 if (fi.getFolder() != null) {
2995 fi.getFolder().bringToFront();
2999 private void growAndFadeOutFolderIcon(FolderIcon fi) {
3000 if (fi == null) return;
3001 PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
3002 PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
3003 PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
3005 FolderInfo info = (FolderInfo) fi.getTag();
3006 if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
3007 CellLayout cl = (CellLayout) fi.getParent().getParent();
3008 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams();
3009 cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY);
3012 // Push an ImageView copy of the FolderIcon into the DragLayer and hide the original
3013 copyFolderIconToImage(fi);
3014 fi.setVisibility(View.INVISIBLE);
3016 ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
3018 if (Utilities.ATLEAST_LOLLIPOP) {
3019 oa.setInterpolator(new LogDecelerateInterpolator(100, 0));
3021 oa.setDuration(getResources().getInteger(R.integer.config_folderExpandDuration));
3025 private void shrinkAndFadeInFolderIcon(final FolderIcon fi) {
3026 if (fi == null) return;
3027 PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
3028 PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
3029 PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
3031 final CellLayout cl = (CellLayout) fi.getParent().getParent();
3033 // We remove and re-draw the FolderIcon in-case it has changed
3034 mDragLayer.removeView(mFolderIconImageView);
3035 copyFolderIconToImage(fi);
3036 ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
3038 oa.setDuration(getResources().getInteger(R.integer.config_folderExpandDuration));
3039 oa.addListener(new AnimatorListenerAdapter() {
3041 public void onAnimationEnd(Animator animation) {
3043 cl.clearFolderLeaveBehind();
3044 // Remove the ImageView copy of the FolderIcon and make the original visible.
3045 mDragLayer.removeView(mFolderIconImageView);
3046 fi.setVisibility(View.VISIBLE);
3054 * Opens the user folder described by the specified tag. The opening of the folder
3055 * is animated relative to the specified View. If the View is null, no animation
3058 * @param folderInfo The FolderInfo describing the folder to open.
3060 public void openFolder(FolderIcon folderIcon) {
3061 Folder folder = folderIcon.getFolder();
3062 Folder openFolder = mWorkspace != null ? mWorkspace.getOpenFolder() : null;
3063 if (openFolder != null && openFolder != folder) {
3064 // Close any open folder before opening a folder.
3068 FolderInfo info = folder.mInfo;
3072 // While the folder is open, the position of the icon cannot change.
3073 ((CellLayout.LayoutParams) folderIcon.getLayoutParams()).canReorder = false;
3075 // Just verify that the folder hasn't already been added to the DragLayer.
3076 // There was a one-off crash where the folder had a parent already.
3077 if (folder.getParent() == null) {
3078 mDragLayer.addView(folder);
3079 mDragController.addDropTarget((DropTarget) folder);
3081 Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" +
3082 folder.getParent() + ").");
3084 folder.animateOpen();
3085 growAndFadeOutFolderIcon(folderIcon);
3087 // Notify the accessibility manager that this folder "window" has appeared and occluded
3088 // the workspace items
3089 folder.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3090 getDragLayer().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
3093 public void closeFolder() {
3094 Folder folder = mWorkspace != null ? mWorkspace.getOpenFolder() : null;
3095 if (folder != null) {
3096 if (folder.isEditingName()) {
3097 folder.dismissEditingName();
3099 closeFolder(folder);
3103 public void closeFolder(Folder folder) {
3104 folder.getInfo().opened = false;
3106 ViewGroup parent = (ViewGroup) folder.getParent().getParent();
3107 if (parent != null) {
3108 FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo);
3109 shrinkAndFadeInFolderIcon(fi);
3111 ((CellLayout.LayoutParams) fi.getLayoutParams()).canReorder = true;
3114 folder.animateClosed();
3116 // Notify the accessibility manager that this folder "window" has disappeard and no
3117 // longer occludeds the workspace items
3118 getDragLayer().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3121 public boolean onLongClick(View v) {
3122 if (!isDraggingEnabled()) return false;
3123 if (isWorkspaceLocked()) return false;
3124 if (mState != State.WORKSPACE) return false;
3126 if (v == mAllAppsButton) {
3127 onLongClickAllAppsButton(v);
3131 if (v instanceof Workspace) {
3132 if (!mWorkspace.isInOverviewMode()) {
3133 if (!mWorkspace.isTouchActive()) {
3134 showOverviewMode(true);
3135 mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
3136 HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
3146 CellLayout.CellInfo longClickCellInfo = null;
3147 View itemUnderLongClick = null;
3148 if (v.getTag() instanceof ItemInfo) {
3149 ItemInfo info = (ItemInfo) v.getTag();
3150 longClickCellInfo = new CellLayout.CellInfo(v, info);
3151 itemUnderLongClick = longClickCellInfo.cell;
3155 // The hotseat touch handling does not go through Workspace, and we always allow long press
3156 // on hotseat items.
3157 final boolean inHotseat = isHotseatLayout(v);
3158 if (!mDragController.isDragging()) {
3159 if (itemUnderLongClick == null) {
3160 // User long pressed on empty space
3161 mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
3162 HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
3163 if (mWorkspace.isInOverviewMode()) {
3164 mWorkspace.startReordering(v);
3166 showOverviewMode(true);
3169 final boolean isAllAppsButton = inHotseat && isAllAppsButtonRank(
3170 mHotseat.getOrderInHotseat(
3171 longClickCellInfo.cellX,
3172 longClickCellInfo.cellY));
3173 if (!(itemUnderLongClick instanceof Folder || isAllAppsButton)) {
3174 // User long pressed on an item
3175 mWorkspace.startDrag(longClickCellInfo);
3182 boolean isHotseatLayout(View layout) {
3183 return mHotseat != null && layout != null &&
3184 (layout instanceof CellLayout) && (layout == mHotseat.getLayout());
3188 * Returns the CellLayout of the specified container at the specified screen.
3190 public CellLayout getCellLayout(long container, long screenId) {
3191 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
3192 if (mHotseat != null) {
3193 return mHotseat.getLayout();
3198 return mWorkspace.getScreenWithId(screenId);
3203 * For overridden classes.
3205 public boolean isAllAppsVisible() {
3206 return isAppsViewVisible();
3209 public boolean isAppsViewVisible() {
3210 return (mState == State.APPS) || (mOnResumeState == State.APPS);
3213 public boolean isWidgetsViewVisible() {
3214 return (mState == State.WIDGETS) || (mOnResumeState == State.WIDGETS);
3217 private void setWorkspaceBackground(int background) {
3218 switch (background) {
3219 case WORKSPACE_BACKGROUND_TRANSPARENT:
3220 getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
3222 case WORKSPACE_BACKGROUND_BLACK:
3223 getWindow().setBackgroundDrawable(null);
3226 getWindow().setBackgroundDrawable(mWorkspaceBackgroundDrawable);
3230 protected void changeWallpaperVisiblity(boolean visible) {
3231 int wpflags = visible ? WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER : 0;
3232 int curflags = getWindow().getAttributes().flags
3233 & WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
3234 if (wpflags != curflags) {
3235 getWindow().setFlags(wpflags, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
3237 setWorkspaceBackground(visible ? WORKSPACE_BACKGROUND_GRADIENT : WORKSPACE_BACKGROUND_BLACK);
3241 public void onTrimMemory(int level) {
3242 super.onTrimMemory(level);
3243 if (level >= ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
3244 // The widget preview db can result in holding onto over
3245 // 3MB of memory for caching which isn't necessary.
3246 SQLiteDatabase.releaseMemory();
3248 // This clears all widget bitmaps from the widget tray
3251 if (mLauncherCallbacks != null) {
3252 mLauncherCallbacks.onTrimMemory(level);
3256 public void showWorkspace(boolean animated) {
3257 showWorkspace(WorkspaceStateTransitionAnimation.SCROLL_TO_CURRENT_PAGE, animated, null);
3260 public void showWorkspace(boolean animated, Runnable onCompleteRunnable) {
3261 showWorkspace(WorkspaceStateTransitionAnimation.SCROLL_TO_CURRENT_PAGE, animated,
3262 onCompleteRunnable);
3265 protected void showWorkspace(int snapToPage, boolean animated) {
3266 showWorkspace(snapToPage, animated, null);
3269 void showWorkspace(int snapToPage, boolean animated, Runnable onCompleteRunnable) {
3270 boolean changed = mState != State.WORKSPACE ||
3271 mWorkspace.getState() != Workspace.State.NORMAL;
3273 mWorkspace.setVisibility(View.VISIBLE);
3274 mStateTransitionAnimation.startAnimationToWorkspace(mState, mWorkspace.getState(),
3275 Workspace.State.NORMAL, snapToPage, animated, onCompleteRunnable);
3277 // Set focus to the AppsCustomize button
3278 if (mAllAppsButton != null) {
3279 mAllAppsButton.requestFocus();
3283 // Change the state *after* we've called all the transition code
3284 mState = State.WORKSPACE;
3286 // Resume the auto-advance of widgets
3287 mUserPresent = true;
3288 updateAutoAdvanceState();
3291 // Send an accessibility event to announce the context change
3292 getWindow().getDecorView()
3293 .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3297 void showOverviewMode(boolean animated) {
3298 mWorkspace.setVisibility(View.VISIBLE);
3299 mStateTransitionAnimation.startAnimationToWorkspace(mState, mWorkspace.getState(),
3300 Workspace.State.OVERVIEW,
3301 WorkspaceStateTransitionAnimation.SCROLL_TO_CURRENT_PAGE, animated,
3302 null /* onCompleteRunnable */);
3303 mState = State.WORKSPACE;
3307 * Shows the apps view.
3309 void showAppsView(boolean animated, boolean resetListToTop, boolean updatePredictedApps,
3310 boolean focusSearchBar) {
3311 if (resetListToTop) {
3312 mAppsView.scrollToTop();
3314 if (updatePredictedApps) {
3315 tryAndUpdatePredictedApps();
3317 showAppsOrWidgets(State.APPS, animated, focusSearchBar);
3321 * Shows the widgets view.
3323 void showWidgetsView(boolean animated, boolean resetPageToZero) {
3324 if (LOGD) Log.d(TAG, "showWidgetsView:" + animated + " resetPageToZero:" + resetPageToZero);
3325 if (resetPageToZero) {
3326 mWidgetsView.scrollToTop();
3328 showAppsOrWidgets(State.WIDGETS, animated, false);
3330 mWidgetsView.post(new Runnable() {
3333 mWidgetsView.requestFocus();
3339 * Sets up the transition to show the apps/widgets view.
3341 * @return whether the current from and to state allowed this operation
3343 // TODO: calling method should use the return value so that when {@code false} is returned
3344 // the workspace transition doesn't fall into invalid state.
3345 private boolean showAppsOrWidgets(State toState, boolean animated, boolean focusSearchBar) {
3346 if (mState != State.WORKSPACE && mState != State.APPS_SPRING_LOADED &&
3347 mState != State.WIDGETS_SPRING_LOADED) {
3350 if (toState != State.APPS && toState != State.WIDGETS) {
3354 if (toState == State.APPS) {
3355 mStateTransitionAnimation.startAnimationToAllApps(mWorkspace.getState(), animated,
3358 mStateTransitionAnimation.startAnimationToWidgets(mWorkspace.getState(), animated);
3361 // Change the state *after* we've called all the transition code
3364 // Pause the auto-advance of widgets until we are out of AllApps
3365 mUserPresent = false;
3366 updateAutoAdvanceState();
3369 // Send an accessibility event to announce the context change
3370 getWindow().getDecorView()
3371 .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3376 * Updates the workspace and interaction state on state change, and return the animation to this
3379 public Animator startWorkspaceStateChangeAnimation(Workspace.State toState, int toPage,
3380 boolean animated, HashMap<View, Integer> layerViews) {
3381 Workspace.State fromState = mWorkspace.getState();
3382 Animator anim = mWorkspace.setStateWithAnimation(toState, toPage, animated, layerViews);
3383 updateInteraction(fromState, toState);
3387 public void enterSpringLoadedDragMode() {
3388 if (LOGD) Log.d(TAG, String.format("enterSpringLoadedDragMode [mState=%s", mState.name()));
3389 if (mState == State.WORKSPACE || mState == State.APPS_SPRING_LOADED ||
3390 mState == State.WIDGETS_SPRING_LOADED) {
3394 mStateTransitionAnimation.startAnimationToWorkspace(mState, mWorkspace.getState(),
3395 Workspace.State.SPRING_LOADED,
3396 WorkspaceStateTransitionAnimation.SCROLL_TO_CURRENT_PAGE, true /* animated */,
3397 null /* onCompleteRunnable */);
3398 mState = isAppsViewVisible() ? State.APPS_SPRING_LOADED : State.WIDGETS_SPRING_LOADED;
3401 public void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, int delay,
3402 final Runnable onCompleteRunnable) {
3403 if (mState != State.APPS_SPRING_LOADED && mState != State.WIDGETS_SPRING_LOADED) return;
3405 mHandler.postDelayed(new Runnable() {
3408 if (successfulDrop) {
3409 // TODO(hyunyoungs): verify if this hack is still needed, if not, delete.
3411 // Before we show workspace, hide all apps again because
3412 // exitSpringLoadedDragMode made it visible. This is a bit hacky; we should
3413 // clean up our state transition functions
3414 mWidgetsView.setVisibility(View.GONE);
3415 showWorkspace(true, onCompleteRunnable);
3417 exitSpringLoadedDragMode();
3423 void exitSpringLoadedDragMode() {
3424 if (mState == State.APPS_SPRING_LOADED) {
3425 showAppsView(true /* animated */, false /* resetListToTop */,
3426 false /* updatePredictedApps */, false /* focusSearchBar */);
3427 } else if (mState == State.WIDGETS_SPRING_LOADED) {
3428 showWidgetsView(true, false);
3433 * Updates the set of predicted apps if it hasn't been updated since the last time Launcher was
3436 private void tryAndUpdatePredictedApps() {
3437 if (mLauncherCallbacks != null) {
3438 List<ComponentKey> apps = mLauncherCallbacks.getPredictedApps();
3440 mAppsView.setPredictedApps(apps);
3445 void lockAllApps() {
3449 void unlockAllApps() {
3453 protected void disableVoiceButtonProxy(boolean disable) {
3457 public View getOrCreateQsbBar() {
3458 if (mLauncherCallbacks != null && mLauncherCallbacks.providesSearch()) {
3459 return mLauncherCallbacks.getQsbBar();
3463 AppWidgetProviderInfo searchProvider = Utilities.getSearchWidgetProvider(this);
3464 if (searchProvider == null) {
3468 Bundle opts = new Bundle();
3469 opts.putInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY,
3470 AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX);
3472 SharedPreferences sp = getSharedPreferences(
3473 LauncherAppState.getSharedPreferencesKey(), MODE_PRIVATE);
3474 int widgetId = sp.getInt(QSB_WIDGET_ID, -1);
3475 AppWidgetProviderInfo widgetInfo = mAppWidgetManager.getAppWidgetInfo(widgetId);
3476 if (!searchProvider.provider.flattenToString().equals(
3477 sp.getString(QSB_WIDGET_PROVIDER, null))
3478 || (widgetInfo == null)
3479 || !widgetInfo.provider.equals(searchProvider.provider)) {
3480 // A valid widget is not already bound.
3481 if (widgetId > -1) {
3482 mAppWidgetHost.deleteAppWidgetId(widgetId);
3486 // Try to bind a new widget
3487 widgetId = mAppWidgetHost.allocateAppWidgetId();
3489 if (!AppWidgetManagerCompat.getInstance(this)
3490 .bindAppWidgetIdIfAllowed(widgetId, searchProvider, opts)) {
3491 mAppWidgetHost.deleteAppWidgetId(widgetId);
3496 .putInt(QSB_WIDGET_ID, widgetId)
3497 .putString(QSB_WIDGET_PROVIDER, searchProvider.provider.flattenToString())
3501 mAppWidgetHost.setQsbWidgetId(widgetId);
3502 if (widgetId != -1) {
3503 mQsb = mAppWidgetHost.createView(this, widgetId, searchProvider);
3504 mQsb.updateAppWidgetOptions(opts);
3505 mQsb.setPadding(0, 0, 0, 0);
3506 mSearchDropTargetBar.addView(mQsb);
3507 mSearchDropTargetBar.setQsbSearchBar(mQsb);
3513 private void reinflateQSBIfNecessary() {
3514 if (mQsb instanceof LauncherAppWidgetHostView &&
3515 ((LauncherAppWidgetHostView) mQsb).isReinflateRequired()) {
3516 mSearchDropTargetBar.removeView(mQsb);
3518 mSearchDropTargetBar.setQsbSearchBar(getOrCreateQsbBar());
3523 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3524 final boolean result = super.dispatchPopulateAccessibilityEvent(event);
3525 final List<CharSequence> text = event.getText();
3527 // Populate event with a fake title based on the current state.
3528 if (mState == State.APPS) {
3529 text.add(getString(R.string.all_apps_button_label));
3530 } else if (mState == State.WIDGETS) {
3531 text.add(getString(R.string.widget_button_text));
3532 } else if (mWorkspace != null) {
3533 text.add(mWorkspace.getCurrentPageDescription());
3535 text.add(getString(R.string.all_apps_home_button_label));
3541 * Receives notifications when system dialogs are to be closed.
3543 @Thunk class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
3545 public void onReceive(Context context, Intent intent) {
3546 closeSystemDialogs();
3551 * If the activity is currently paused, signal that we need to run the passed Runnable
3554 * This needs to be called from incoming places where resources might have been loaded
3555 * while the activity is paused. That is because the Configuration (e.g., rotation) might be
3556 * wrong when we're not running, and if the activity comes back to what the configuration was
3557 * when we were paused, activity is not restarted.
3559 * Implementation of the method from LauncherModel.Callbacks.
3561 * @return {@code true} if we are currently paused. The caller might be able to skip some work
3563 @Thunk boolean waitUntilResume(Runnable run, boolean deletePreviousRunnables) {
3565 if (LOGD) Log.d(TAG, "Deferring update until onResume");
3566 if (deletePreviousRunnables) {
3567 while (mBindOnResumeCallbacks.remove(run)) {
3570 mBindOnResumeCallbacks.add(run);
3577 private boolean waitUntilResume(Runnable run) {
3578 return waitUntilResume(run, false);
3581 public void addOnResumeCallback(Runnable run) {
3582 mOnResumeCallbacks.add(run);
3586 * If the activity is currently paused, signal that we need to re-run the loader
3589 * This needs to be called from incoming places where resources might have been loaded
3590 * while we are paused. That is becaues the Configuration might be wrong
3591 * when we're not running, and if it comes back to what it was when we
3592 * were paused, we are not restarted.
3594 * Implementation of the method from LauncherModel.Callbacks.
3596 * @return true if we are currently paused. The caller might be able to
3597 * skip some work in that case since we will come back again.
3599 public boolean setLoadOnResume() {
3601 if (LOGD) Log.d(TAG, "setLoadOnResume");
3602 mOnResumeNeedsLoad = true;
3610 * Implementation of the method from LauncherModel.Callbacks.
3612 public int getCurrentWorkspaceScreen() {
3613 if (mWorkspace != null) {
3614 return mWorkspace.getCurrentPage();
3616 return SCREEN_COUNT / 2;
3621 * Refreshes the shortcuts shown on the workspace.
3623 * Implementation of the method from LauncherModel.Callbacks.
3625 public void startBinding() {
3626 setWorkspaceLoading(true);
3628 // If we're starting binding all over again, clear any bind calls we'd postponed in
3629 // the past (see waitUntilResume) -- we don't need them since we're starting binding
3630 // from scratch again
3631 mBindOnResumeCallbacks.clear();
3633 // Clear the workspace because it's going to be rebound
3634 mWorkspace.clearDropTargets();
3635 mWorkspace.removeAllWorkspaceScreens();
3637 mWidgetsToAdvance.clear();
3638 if (mHotseat != null) {
3639 mHotseat.resetLayout();
3644 public void bindScreens(ArrayList<Long> orderedScreenIds) {
3645 bindAddScreens(orderedScreenIds);
3647 // If there are no screens, we need to have an empty screen
3648 if (orderedScreenIds.size() == 0) {
3649 mWorkspace.addExtraEmptyScreen();
3652 // Create the custom content page (this call updates mDefaultScreen which calls
3653 // setCurrentPage() so ensure that all pages are added before calling this).
3654 if (hasCustomContentToLeft()) {
3655 mWorkspace.createCustomContentContainer();
3656 populateCustomContentContainer();
3661 public void bindAddScreens(ArrayList<Long> orderedScreenIds) {
3662 int count = orderedScreenIds.size();
3663 for (int i = 0; i < count; i++) {
3664 mWorkspace.insertNewWorkspaceScreenBeforeEmptyScreen(orderedScreenIds.get(i));
3668 private boolean shouldShowWeightWatcher() {
3669 String spKey = LauncherAppState.getSharedPreferencesKey();
3670 SharedPreferences sp = getSharedPreferences(spKey, Context.MODE_PRIVATE);
3671 boolean show = sp.getBoolean(SHOW_WEIGHT_WATCHER, SHOW_WEIGHT_WATCHER_DEFAULT);
3676 private void toggleShowWeightWatcher() {
3677 String spKey = LauncherAppState.getSharedPreferencesKey();
3678 SharedPreferences sp = getSharedPreferences(spKey, Context.MODE_PRIVATE);
3679 boolean show = sp.getBoolean(SHOW_WEIGHT_WATCHER, true);
3683 SharedPreferences.Editor editor = sp.edit();
3684 editor.putBoolean(SHOW_WEIGHT_WATCHER, show);
3687 if (mWeightWatcher != null) {
3688 mWeightWatcher.setVisibility(show ? View.VISIBLE : View.GONE);
3692 public void bindAppsAdded(final ArrayList<Long> newScreens,
3693 final ArrayList<ItemInfo> addNotAnimated,
3694 final ArrayList<ItemInfo> addAnimated,
3695 final ArrayList<AppInfo> addedApps) {
3696 Runnable r = new Runnable() {
3698 bindAppsAdded(newScreens, addNotAnimated, addAnimated, addedApps);
3701 if (waitUntilResume(r)) {
3705 // Add the new screens
3706 if (newScreens != null) {
3707 bindAddScreens(newScreens);
3710 // We add the items without animation on non-visible pages, and with
3711 // animations on the new page (which we will try and snap to).
3712 if (addNotAnimated != null && !addNotAnimated.isEmpty()) {
3713 bindItems(addNotAnimated, 0,
3714 addNotAnimated.size(), false);
3716 if (addAnimated != null && !addAnimated.isEmpty()) {
3717 bindItems(addAnimated, 0,
3718 addAnimated.size(), true);
3721 // Remove the extra empty screen
3722 mWorkspace.removeExtraEmptyScreen(false, false);
3724 if (addedApps != null && mAppsView != null) {
3725 mAppsView.addApps(addedApps);
3730 * Bind the items start-end from the list.
3732 * Implementation of the method from LauncherModel.Callbacks.
3734 public void bindItems(final ArrayList<ItemInfo> shortcuts, final int start, final int end,
3735 final boolean forceAnimateIcons) {
3736 Runnable r = new Runnable() {
3738 bindItems(shortcuts, start, end, forceAnimateIcons);
3741 if (waitUntilResume(r)) {
3745 // Get the list of added shortcuts and intersect them with the set of shortcuts here
3746 final AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
3747 final Collection<Animator> bounceAnims = new ArrayList<Animator>();
3748 final boolean animateIcons = forceAnimateIcons && canRunNewAppsAnimation();
3749 Workspace workspace = mWorkspace;
3750 long newShortcutsScreenId = -1;
3751 for (int i = start; i < end; i++) {
3752 final ItemInfo item = shortcuts.get(i);
3754 // Short circuit if we are loading dock items for a configuration which has no dock
3755 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
3761 switch (item.itemType) {
3762 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3763 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3764 ShortcutInfo info = (ShortcutInfo) item;
3765 view = createShortcut(info);
3768 * TODO: FIX collision case
3770 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
3771 CellLayout cl = mWorkspace.getScreenWithId(item.screenId);
3772 if (cl != null && cl.isOccupied(item.cellX, item.cellY)) {
3773 View v = cl.getChildAt(item.cellX, item.cellY);
3774 Object tag = v.getTag();
3775 String desc = "Collision while binding workspace item: " + item
3776 + ". Collides with " + tag;
3777 if (LauncherAppState.isDogfoodBuild()) {
3778 throw (new RuntimeException(desc));
3785 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3786 view = FolderIcon.fromXml(R.layout.folder_icon, this,
3787 (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
3788 (FolderInfo) item, mIconCache);
3791 throw new RuntimeException("Invalid Item Type");
3794 workspace.addInScreenFromBind(view, item.container, item.screenId, item.cellX,
3797 // Animate all the applications up now
3801 bounceAnims.add(createNewAppBounceAnimation(view, i));
3802 newShortcutsScreenId = item.screenId;
3807 // Animate to the correct page
3808 if (newShortcutsScreenId > -1) {
3809 long currentScreenId = mWorkspace.getScreenIdForPageIndex(mWorkspace.getNextPage());
3810 final int newScreenIndex = mWorkspace.getPageIndexForScreenId(newShortcutsScreenId);
3811 final Runnable startBounceAnimRunnable = new Runnable() {
3813 anim.playTogether(bounceAnims);
3817 if (newShortcutsScreenId != currentScreenId) {
3818 // We post the animation slightly delayed to prevent slowdowns
3819 // when we are loading right after we return to launcher.
3820 mWorkspace.postDelayed(new Runnable() {
3822 if (mWorkspace != null) {
3823 mWorkspace.snapToPage(newScreenIndex);
3824 mWorkspace.postDelayed(startBounceAnimRunnable,
3825 NEW_APPS_ANIMATION_DELAY);
3828 }, NEW_APPS_PAGE_MOVE_DELAY);
3830 mWorkspace.postDelayed(startBounceAnimRunnable, NEW_APPS_ANIMATION_DELAY);
3834 workspace.requestLayout();
3838 * Implementation of the method from LauncherModel.Callbacks.
3840 public void bindFolders(final LongArrayMap<FolderInfo> folders) {
3841 Runnable r = new Runnable() {
3843 bindFolders(folders);
3846 if (waitUntilResume(r)) {
3849 sFolders = folders.clone();
3853 * Add the views for a widget to the workspace.
3855 * Implementation of the method from LauncherModel.Callbacks.
3857 public void bindAppWidget(final LauncherAppWidgetInfo item) {
3858 Runnable r = new Runnable() {
3860 bindAppWidget(item);
3863 if (waitUntilResume(r)) {
3867 final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
3868 if (DEBUG_WIDGETS) {
3869 Log.d(TAG, "bindAppWidget: " + item);
3871 final Workspace workspace = mWorkspace;
3873 LauncherAppWidgetProviderInfo appWidgetInfo =
3874 LauncherModel.getProviderInfo(this, item.providerName, item.user);
3876 if (!mIsSafeModeEnabled
3877 && ((item.restoreStatus & LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0)
3878 && (item.restoreStatus != LauncherAppWidgetInfo.RESTORE_COMPLETED)) {
3880 if (appWidgetInfo == null) {
3881 if (DEBUG_WIDGETS) {
3882 Log.d(TAG, "Removing restored widget: id=" + item.appWidgetId
3883 + " belongs to component " + item.providerName
3884 + ", as the povider is null");
3886 LauncherModel.deleteItemFromDatabase(this, item);
3890 // If we do not have a valid id, try to bind an id.
3891 if ((item.restoreStatus & LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) != 0) {
3892 // Note: This assumes that the id remap broadcast is received before this step.
3893 // If that is not the case, the id remap will be ignored and user may see the
3894 // click to setup view.
3895 PendingAddWidgetInfo pendingInfo = new PendingAddWidgetInfo(this, appWidgetInfo, null);
3896 pendingInfo.spanX = item.spanX;
3897 pendingInfo.spanY = item.spanY;
3898 pendingInfo.minSpanX = item.minSpanX;
3899 pendingInfo.minSpanY = item.minSpanY;
3900 Bundle options = null;
3901 WidgetHostViewLoader.getDefaultOptionsForWidget(this, pendingInfo);
3903 int newWidgetId = mAppWidgetHost.allocateAppWidgetId();
3904 boolean success = mAppWidgetManager.bindAppWidgetIdIfAllowed(
3905 newWidgetId, appWidgetInfo, options);
3907 // TODO consider showing a permission dialog when the widget is clicked.
3909 mAppWidgetHost.deleteAppWidgetId(newWidgetId);
3910 if (DEBUG_WIDGETS) {
3911 Log.d(TAG, "Removing restored widget: id=" + item.appWidgetId
3912 + " belongs to component " + item.providerName
3913 + ", as the launcher is unable to bing a new widget id");
3915 LauncherModel.deleteItemFromDatabase(this, item);
3919 item.appWidgetId = newWidgetId;
3921 // If the widget has a configure activity, it is still needs to set it up, otherwise
3922 // the widget is ready to go.
3923 item.restoreStatus = (appWidgetInfo.configure == null)
3924 ? LauncherAppWidgetInfo.RESTORE_COMPLETED
3925 : LauncherAppWidgetInfo.FLAG_UI_NOT_READY;
3927 LauncherModel.updateItemInDatabase(this, item);
3928 } else if (((item.restoreStatus & LauncherAppWidgetInfo.FLAG_UI_NOT_READY) != 0)
3929 && (appWidgetInfo.configure == null)) {
3930 // If the ID is already valid, verify if we need to configure or not.
3931 item.restoreStatus = LauncherAppWidgetInfo.RESTORE_COMPLETED;
3932 LauncherModel.updateItemInDatabase(this, item);
3936 if (!mIsSafeModeEnabled && item.restoreStatus == LauncherAppWidgetInfo.RESTORE_COMPLETED) {
3937 final int appWidgetId = item.appWidgetId;
3938 if (DEBUG_WIDGETS) {
3939 Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component "
3940 + appWidgetInfo.provider);
3943 item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
3944 item.minSpanX = appWidgetInfo.minSpanX;
3945 item.minSpanY = appWidgetInfo.minSpanY;
3947 appWidgetInfo = null;
3948 PendingAppWidgetHostView view = new PendingAppWidgetHostView(this, item,
3949 mIsSafeModeEnabled);
3950 view.updateIcon(mIconCache);
3951 item.hostView = view;
3952 item.hostView.updateAppWidget(null);
3953 item.hostView.setOnClickListener(this);
3956 item.hostView.setTag(item);
3957 item.onBindAppWidget(this);
3959 workspace.addInScreen(item.hostView, item.container, item.screenId, item.cellX,
3960 item.cellY, item.spanX, item.spanY, false);
3961 if (!item.isCustomWidget()) {
3962 addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
3965 workspace.requestLayout();
3967 if (DEBUG_WIDGETS) {
3968 Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
3969 + (SystemClock.uptimeMillis()-start) + "ms");
3974 * Restores a pending widget.
3976 * @param appWidgetId The app widget id
3977 * @param cellInfo The position on screen where to create the widget.
3979 private void completeRestoreAppWidget(final int appWidgetId) {
3980 LauncherAppWidgetHostView view = mWorkspace.getWidgetForAppWidgetId(appWidgetId);
3981 if ((view == null) || !(view instanceof PendingAppWidgetHostView)) {
3982 Log.e(TAG, "Widget update called, when the widget no longer exists.");
3986 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) view.getTag();
3987 info.restoreStatus = LauncherAppWidgetInfo.RESTORE_COMPLETED;
3989 mWorkspace.reinflateWidgetsIfNecessary();
3990 LauncherModel.updateItemInDatabase(this, info);
3993 public void onPageBoundSynchronously(int page) {
3994 mSynchronouslyBoundPages.add(page);
3998 * Callback saying that there aren't any more items to bind.
4000 * Implementation of the method from LauncherModel.Callbacks.
4002 public void finishBindingItems() {
4003 Runnable r = new Runnable() {
4005 finishBindingItems();
4008 if (waitUntilResume(r)) {
4011 if (mSavedState != null) {
4012 if (!mWorkspace.hasFocus()) {
4013 mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
4018 mWorkspace.restoreInstanceStateForRemainingPages();
4020 setWorkspaceLoading(false);
4021 sendLoadingCompleteBroadcastIfNecessary();
4023 // If we received the result of any pending adds while the loader was running (e.g. the
4024 // widget configuration forced an orientation change), process them now.
4025 if (sPendingAddItem != null) {
4026 final long screenId = completeAdd(sPendingAddItem);
4028 // TODO: this moves the user to the page where the pending item was added. Ideally,
4029 // the screen would be guaranteed to exist after bind, and the page would be set through
4030 // the workspace restore process.
4031 mWorkspace.post(new Runnable() {
4034 mWorkspace.snapToScreenId(screenId);
4037 sPendingAddItem = null;
4040 InstallShortcutReceiver.disableAndFlushInstallQueue(this);
4042 if (mLauncherCallbacks != null) {
4043 mLauncherCallbacks.finishBindingItems(false);
4047 private void sendLoadingCompleteBroadcastIfNecessary() {
4048 if (!mSharedPrefs.getBoolean(FIRST_LOAD_COMPLETE, false)) {
4050 getResources().getString(R.string.receive_first_load_broadcast_permission);
4051 Intent intent = new Intent(ACTION_FIRST_LOAD_COMPLETE);
4052 sendBroadcast(intent, permission);
4053 SharedPreferences.Editor editor = mSharedPrefs.edit();
4054 editor.putBoolean(FIRST_LOAD_COMPLETE, true);
4059 public boolean isAllAppsButtonRank(int rank) {
4060 if (mHotseat != null) {
4061 return mHotseat.isAllAppsButtonRank(rank);
4066 private boolean canRunNewAppsAnimation() {
4067 long diff = System.currentTimeMillis() - mDragController.getLastGestureUpTime();
4068 return diff > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000)
4069 && (mClings == null || !mClings.isVisible());
4072 private ValueAnimator createNewAppBounceAnimation(View v, int i) {
4073 ValueAnimator bounceAnim = LauncherAnimUtils.ofPropertyValuesHolder(v,
4074 PropertyValuesHolder.ofFloat("alpha", 1f),
4075 PropertyValuesHolder.ofFloat("scaleX", 1f),
4076 PropertyValuesHolder.ofFloat("scaleY", 1f));
4077 bounceAnim.setDuration(InstallShortcutReceiver.NEW_SHORTCUT_BOUNCE_DURATION);
4078 bounceAnim.setStartDelay(i * InstallShortcutReceiver.NEW_SHORTCUT_STAGGER_DELAY);
4079 bounceAnim.setInterpolator(new OvershootInterpolator(BOUNCE_ANIMATION_TENSION));
4083 public boolean useVerticalBarLayout() {
4084 return mDeviceProfile.isVerticalBarLayout();
4087 protected Rect getSearchBarBounds() {
4088 return mDeviceProfile.getSearchBarBounds(Utilities.isRtl(getResources()));
4091 public void bindSearchProviderChanged() {
4092 if (mSearchDropTargetBar == null) {
4096 mSearchDropTargetBar.removeView(mQsb);
4099 mSearchDropTargetBar.setQsbSearchBar(getOrCreateQsbBar());
4103 * A runnable that we can dequeue and re-enqueue when all applications are bound (to prevent
4104 * multiple calls to bind the same list.)
4106 @Thunk ArrayList<AppInfo> mTmpAppsList;
4107 private Runnable mBindAllApplicationsRunnable = new Runnable() {
4109 bindAllApplications(mTmpAppsList);
4110 mTmpAppsList = null;
4115 * Add the icons for all apps.
4117 * Implementation of the method from LauncherModel.Callbacks.
4119 public void bindAllApplications(final ArrayList<AppInfo> apps) {
4120 if (waitUntilResume(mBindAllApplicationsRunnable, true)) {
4121 mTmpAppsList = apps;
4125 if (mAppsView != null) {
4126 mAppsView.setApps(apps);
4128 if (mLauncherCallbacks != null) {
4129 mLauncherCallbacks.bindAllApplications(apps);
4134 * A package was updated.
4136 * Implementation of the method from LauncherModel.Callbacks.
4138 public void bindAppsUpdated(final ArrayList<AppInfo> apps) {
4139 Runnable r = new Runnable() {
4141 bindAppsUpdated(apps);
4144 if (waitUntilResume(r)) {
4148 if (mAppsView != null) {
4149 mAppsView.updateApps(apps);
4154 public void bindWidgetsRestored(final ArrayList<LauncherAppWidgetInfo> widgets) {
4155 Runnable r = new Runnable() {
4157 bindWidgetsRestored(widgets);
4160 if (waitUntilResume(r)) {
4163 mWorkspace.widgetsRestored(widgets);
4167 * Some shortcuts were updated in the background.
4169 * Implementation of the method from LauncherModel.Callbacks.
4172 public void bindShortcutsChanged(final ArrayList<ShortcutInfo> updated,
4173 final ArrayList<ShortcutInfo> removed, final UserHandleCompat user) {
4174 Runnable r = new Runnable() {
4176 bindShortcutsChanged(updated, removed, user);
4179 if (waitUntilResume(r)) {
4183 if (!updated.isEmpty()) {
4184 mWorkspace.updateShortcuts(updated);
4187 if (!removed.isEmpty()) {
4188 HashSet<ComponentName> removedComponents = new HashSet<ComponentName>();
4189 for (ShortcutInfo si : removed) {
4190 removedComponents.add(si.getTargetComponent());
4192 mWorkspace.removeItemsByComponentName(removedComponents, user);
4193 // Notify the drag controller
4194 mDragController.onAppsRemoved(new ArrayList<String>(), removedComponents);
4199 * Update the state of a package, typically related to install state.
4201 * Implementation of the method from LauncherModel.Callbacks.
4204 public void bindRestoreItemsChange(final HashSet<ItemInfo> updates) {
4205 Runnable r = new Runnable() {
4207 bindRestoreItemsChange(updates);
4210 if (waitUntilResume(r)) {
4214 mWorkspace.updateRestoreItems(updates);
4218 * A package was uninstalled. We take both the super set of packageNames
4219 * in addition to specific applications to remove, the reason being that
4220 * this can be called when a package is updated as well. In that scenario,
4221 * we only remove specific components from the workspace, where as
4222 * package-removal should clear all items by package name.
4224 * @param reason if non-zero, the icons are not permanently removed, rather marked as disabled.
4225 * Implementation of the method from LauncherModel.Callbacks.
4228 public void bindComponentsRemoved(final ArrayList<String> packageNames,
4229 final ArrayList<AppInfo> appInfos, final UserHandleCompat user, final int reason) {
4230 Runnable r = new Runnable() {
4232 bindComponentsRemoved(packageNames, appInfos, user, reason);
4235 if (waitUntilResume(r)) {
4240 HashSet<ComponentName> removedComponents = new HashSet<ComponentName>();
4241 for (AppInfo info : appInfos) {
4242 removedComponents.add(info.componentName);
4244 if (!packageNames.isEmpty()) {
4245 mWorkspace.removeItemsByPackageName(packageNames, user);
4247 if (!removedComponents.isEmpty()) {
4248 mWorkspace.removeItemsByComponentName(removedComponents, user);
4250 // Notify the drag controller
4251 mDragController.onAppsRemoved(packageNames, removedComponents);
4254 mWorkspace.disableShortcutsByPackageName(packageNames, user, reason);
4258 if (mAppsView != null) {
4259 mAppsView.removeApps(appInfos);
4263 private Runnable mBindPackagesUpdatedRunnable = new Runnable() {
4265 bindAllPackages(mWidgetsModel);
4270 public void bindAllPackages(final WidgetsModel model) {
4271 if (waitUntilResume(mBindPackagesUpdatedRunnable, true)) {
4272 mWidgetsModel = model;
4276 if (mWidgetsView != null && model != null) {
4277 mWidgetsView.addWidgets(model);
4278 mWidgetsModel = null;
4282 private int mapConfigurationOriActivityInfoOri(int configOri) {
4283 final Display d = getWindowManager().getDefaultDisplay();
4284 int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
4285 switch (d.getRotation()) {
4286 case Surface.ROTATION_0:
4287 case Surface.ROTATION_180:
4288 // We are currently in the same basic orientation as the natural orientation
4289 naturalOri = configOri;
4291 case Surface.ROTATION_90:
4292 case Surface.ROTATION_270:
4293 // We are currently in the other basic orientation to the natural orientation
4294 naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
4295 Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
4300 ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
4301 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
4302 ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
4303 ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
4305 // Since the map starts at portrait, we need to offset if this device's natural orientation
4307 int indexOffset = 0;
4308 if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
4311 return oriMap[(d.getRotation() + indexOffset) % 4];
4314 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
4315 public void lockScreenOrientation() {
4316 if (mRotationEnabled) {
4317 if (Utilities.ATLEAST_JB_MR2) {
4318 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
4320 setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
4321 .getConfiguration().orientation));
4326 public void unlockScreenOrientation(boolean immediate) {
4327 if (mRotationEnabled) {
4329 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
4331 mHandler.postDelayed(new Runnable() {
4333 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
4335 }, mRestoreScreenOrientationDelay);
4340 protected boolean isLauncherPreinstalled() {
4341 if (mLauncherCallbacks != null) {
4342 return mLauncherCallbacks.isLauncherPreinstalled();
4344 PackageManager pm = getPackageManager();
4346 ApplicationInfo ai = pm.getApplicationInfo(getComponentName().getPackageName(), 0);
4347 if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4352 } catch (NameNotFoundException e) {
4353 e.printStackTrace();
4359 * This method indicates whether or not we should suggest default wallpaper dimensions
4360 * when our wallpaper cropper was not yet used to set a wallpaper.
4362 protected boolean overrideWallpaperDimensions() {
4363 if (mLauncherCallbacks != null) {
4364 return mLauncherCallbacks.overrideWallpaperDimensions();
4370 * To be overridden by subclasses to indicate that there is an activity to launch
4371 * before showing the standard launcher experience.
4373 protected boolean hasFirstRunActivity() {
4374 if (mLauncherCallbacks != null) {
4375 return mLauncherCallbacks.hasFirstRunActivity();
4381 * To be overridden by subclasses to launch any first run activity
4383 protected Intent getFirstRunActivity() {
4384 if (mLauncherCallbacks != null) {
4385 return mLauncherCallbacks.getFirstRunActivity();
4390 private boolean shouldRunFirstRunActivity() {
4391 return !ActivityManager.isRunningInTestHarness() &&
4392 !mSharedPrefs.getBoolean(FIRST_RUN_ACTIVITY_DISPLAYED, false);
4395 protected boolean hasRunFirstRunActivity() {
4396 return mSharedPrefs.getBoolean(FIRST_RUN_ACTIVITY_DISPLAYED, false);
4399 public boolean showFirstRunActivity() {
4400 if (shouldRunFirstRunActivity() &&
4401 hasFirstRunActivity()) {
4402 Intent firstRunIntent = getFirstRunActivity();
4403 if (firstRunIntent != null) {
4404 startActivity(firstRunIntent);
4405 markFirstRunActivityShown();
4412 private void markFirstRunActivityShown() {
4413 SharedPreferences.Editor editor = mSharedPrefs.edit();
4414 editor.putBoolean(FIRST_RUN_ACTIVITY_DISPLAYED, true);
4419 * To be overridden by subclasses to indicate that there is an in-activity full-screen intro
4420 * screen that must be displayed and dismissed.
4422 protected boolean hasDismissableIntroScreen() {
4423 if (mLauncherCallbacks != null) {
4424 return mLauncherCallbacks.hasDismissableIntroScreen();
4430 * Full screen intro screen to be shown and dismissed before the launcher can be used.
4432 protected View getIntroScreen() {
4433 if (mLauncherCallbacks != null) {
4434 return mLauncherCallbacks.getIntroScreen();
4440 * To be overriden by subclasses to indicate whether the in-activity intro screen has been
4441 * dismissed. This method is ignored if #hasDismissableIntroScreen returns false.
4443 private boolean shouldShowIntroScreen() {
4444 return hasDismissableIntroScreen() &&
4445 !mSharedPrefs.getBoolean(INTRO_SCREEN_DISMISSED, false);
4448 protected void showIntroScreen() {
4449 View introScreen = getIntroScreen();
4450 changeWallpaperVisiblity(false);
4451 if (introScreen != null) {
4452 mDragLayer.showOverlayView(introScreen);
4454 if (mLauncherOverlayContainer != null) {
4455 mLauncherOverlayContainer.setVisibility(View.INVISIBLE);
4459 public void dismissIntroScreen() {
4460 markIntroScreenDismissed();
4461 if (showFirstRunActivity()) {
4462 // We delay hiding the intro view until the first run activity is showing. This
4464 mWorkspace.postDelayed(new Runnable() {
4467 mDragLayer.dismissOverlayView();
4468 if (mLauncherOverlayContainer != null) {
4469 mLauncherOverlayContainer.setVisibility(View.VISIBLE);
4471 showFirstRunClings();
4473 }, ACTIVITY_START_DELAY);
4475 mDragLayer.dismissOverlayView();
4476 if (mLauncherOverlayContainer != null) {
4477 mLauncherOverlayContainer.setVisibility(View.VISIBLE);
4479 showFirstRunClings();
4481 changeWallpaperVisiblity(true);
4484 private void markIntroScreenDismissed() {
4485 SharedPreferences.Editor editor = mSharedPrefs.edit();
4486 editor.putBoolean(INTRO_SCREEN_DISMISSED, true);
4490 @Thunk void showFirstRunClings() {
4491 // The two first run cling paths are mutually exclusive, if the launcher is preinstalled
4492 // on the device, then we always show the first run cling experience (or if there is no
4493 // launcher2). Otherwise, we prompt the user upon started for migration
4494 LauncherClings launcherClings = new LauncherClings(this);
4495 if (launcherClings.shouldShowFirstRunOrMigrationClings()) {
4496 mClings = launcherClings;
4497 if (mModel.canMigrateFromOldLauncherDb(this)) {
4498 launcherClings.showMigrationCling();
4500 launcherClings.showLongPressCling(true);
4505 void showWorkspaceSearchAndHotseat() {
4506 if (mWorkspace != null) mWorkspace.setAlpha(1f);
4507 if (mHotseat != null) mHotseat.setAlpha(1f);
4508 if (mPageIndicators != null) mPageIndicators.setAlpha(1f);
4509 if (mSearchDropTargetBar != null) mSearchDropTargetBar.animateToState(
4510 SearchDropTargetBar.State.SEARCH_BAR, 0);
4513 void hideWorkspaceSearchAndHotseat() {
4514 if (mWorkspace != null) mWorkspace.setAlpha(0f);
4515 if (mHotseat != null) mHotseat.setAlpha(0f);
4516 if (mPageIndicators != null) mPageIndicators.setAlpha(0f);
4517 if (mSearchDropTargetBar != null) mSearchDropTargetBar.animateToState(
4518 SearchDropTargetBar.State.INVISIBLE, 0);
4521 // TODO: These method should be a part of LauncherSearchCallback
4522 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
4523 public ItemInfo createAppDragInfo(Intent appLaunchIntent) {
4524 // Called from search suggestion
4525 UserHandleCompat user = null;
4526 if (Utilities.ATLEAST_LOLLIPOP) {
4527 UserHandle userHandle = appLaunchIntent.getParcelableExtra(Intent.EXTRA_USER);
4528 if (userHandle != null) {
4529 user = UserHandleCompat.fromUser(userHandle);
4532 return createAppDragInfo(appLaunchIntent, user);
4535 // TODO: This method should be a part of LauncherSearchCallback
4536 public ItemInfo createAppDragInfo(Intent intent, UserHandleCompat user) {
4538 user = UserHandleCompat.myUserHandle();
4541 // Called from search suggestion, add the profile extra to the intent to ensure that we
4542 // can launch it correctly
4543 LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this);
4544 LauncherActivityInfoCompat activityInfo = launcherApps.resolveActivity(intent, user);
4545 if (activityInfo == null) {
4548 return new AppInfo(this, activityInfo, user, mIconCache);
4551 // TODO: This method should be a part of LauncherSearchCallback
4552 public ItemInfo createShortcutDragInfo(Intent shortcutIntent, CharSequence caption,
4554 return new ShortcutInfo(shortcutIntent, caption, caption, icon,
4555 UserHandleCompat.myUserHandle());
4558 // TODO: This method should be a part of LauncherSearchCallback
4559 public void startDrag(View dragView, ItemInfo dragInfo, DragSource source) {
4560 dragView.setTag(dragInfo);
4561 mWorkspace.onExternalDragStartedWithItem(dragView);
4562 mWorkspace.beginExternalDragShared(dragView, source);
4565 protected void moveWorkspaceToDefaultScreen() {
4566 mWorkspace.moveToDefaultScreen(false);
4570 public void onPageSwitch(View newPage, int newPageIndex) {
4571 if (mLauncherCallbacks != null) {
4572 mLauncherCallbacks.onPageSwitch(newPage, newPageIndex);
4577 * Returns a FastBitmapDrawable with the icon, accurately sized.
4579 public FastBitmapDrawable createIconDrawable(Bitmap icon) {
4580 FastBitmapDrawable d = new FastBitmapDrawable(icon);
4581 d.setFilterBitmap(true);
4582 resizeIconDrawable(d);
4587 * Resizes an icon drawable to the correct icon size.
4589 public void resizeIconDrawable(Drawable icon) {
4590 icon.setBounds(0, 0, mDeviceProfile.iconSizePx, mDeviceProfile.iconSizePx);
4594 * Prints out out state for debugging.
4596 public void dumpState() {
4597 Log.d(TAG, "BEGIN launcher3 dump state for launcher " + this);
4598 Log.d(TAG, "mSavedState=" + mSavedState);
4599 Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
4600 Log.d(TAG, "mRestoring=" + mRestoring);
4601 Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
4602 Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
4603 Log.d(TAG, "sFolders.size=" + sFolders.size());
4605 // TODO(hyunyoungs): add mWidgetsView.dumpState(); or mWidgetsModel.dumpState();
4607 Log.d(TAG, "END launcher3 dump state");
4611 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
4612 super.dump(prefix, fd, writer, args);
4613 synchronized (sDumpLogs) {
4614 writer.println(" ");
4615 writer.println("Debug logs: ");
4616 for (int i = 0; i < sDumpLogs.size(); i++) {
4617 writer.println(" " + sDumpLogs.get(i));
4620 if (mLauncherCallbacks != null) {
4621 mLauncherCallbacks.dump(prefix, fd, writer, args);
4625 public static void dumpDebugLogsToConsole() {
4626 if (DEBUG_DUMP_LOG) {
4627 synchronized (sDumpLogs) {
4629 Log.d(TAG, "*********************");
4630 Log.d(TAG, "Launcher debug logs: ");
4631 for (int i = 0; i < sDumpLogs.size(); i++) {
4632 Log.d(TAG, " " + sDumpLogs.get(i));
4634 Log.d(TAG, "*********************");
4640 public static void addDumpLog(String tag, String log, boolean debugLog) {
4641 addDumpLog(tag, log, null, debugLog);
4644 public static void addDumpLog(String tag, String log, Exception e, boolean debugLog) {
4652 if (DEBUG_DUMP_LOG) {
4653 sDateStamp.setTime(System.currentTimeMillis());
4654 synchronized (sDumpLogs) {
4655 sDumpLogs.add(sDateFormat.format(sDateStamp) + ": " + tag + ", " + log
4656 + (e == null ? "" : (", Exception: " + e)));
4661 public static CustomAppWidget getCustomAppWidget(String name) {
4662 return sCustomAppWidgets.get(name);
4665 public static HashMap<String, CustomAppWidget> getCustomAppWidgets() {
4666 return sCustomAppWidgets;
4669 public void dumpLogsToLocalData() {
4670 if (DEBUG_DUMP_LOG) {
4671 new AsyncTask<Void, Void, Void>() {
4672 public Void doInBackground(Void ... args) {
4673 boolean success = false;
4674 sDateStamp.setTime(sRunStart);
4675 String FILENAME = sDateStamp.getMonth() + "-"
4676 + sDateStamp.getDay() + "_"
4677 + sDateStamp.getHours() + "-"
4678 + sDateStamp.getMinutes() + "_"
4679 + sDateStamp.getSeconds() + ".txt";
4681 FileOutputStream fos = null;
4682 File outFile = null;
4684 outFile = new File(getFilesDir(), FILENAME);
4685 outFile.createNewFile();
4686 fos = new FileOutputStream(outFile);
4687 } catch (Exception e) {
4688 e.printStackTrace();
4691 PrintWriter writer = new PrintWriter(fos);
4693 writer.println(" ");
4694 writer.println("Debug logs: ");
4695 synchronized (sDumpLogs) {
4696 for (int i = 0; i < sDumpLogs.size(); i++) {
4697 writer.println(" " + sDumpLogs.get(i));
4707 } catch (IOException e) {
4708 e.printStackTrace();
4712 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
4717 interface DebugIntents {
4718 static final String DELETE_DATABASE = "com.android.launcher3.action.DELETE_DATABASE";
4719 static final String MIGRATE_DATABASE = "com.android.launcher3.action.MIGRATE_DATABASE";