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.Manifest;
20 import android.animation.Animator;
21 import android.animation.AnimatorListenerAdapter;
22 import android.animation.AnimatorSet;
23 import android.animation.ObjectAnimator;
24 import android.animation.PropertyValuesHolder;
25 import android.animation.ValueAnimator;
26 import android.annotation.SuppressLint;
27 import android.annotation.TargetApi;
28 import android.app.Activity;
29 import android.app.ActivityManager;
30 import android.app.ActivityOptions;
31 import android.app.AlertDialog;
32 import android.app.Fragment;
33 import android.app.FragmentManager;
34 import android.app.FragmentTransaction;
35 import android.app.SearchManager;
36 import android.appwidget.AppWidgetHostView;
37 import android.appwidget.AppWidgetManager;
38 import android.appwidget.AppWidgetProviderInfo;
39 import android.content.ActivityNotFoundException;
40 import android.content.BroadcastReceiver;
41 import android.content.ComponentCallbacks2;
42 import android.content.ComponentName;
43 import android.content.Context;
44 import android.content.ContextWrapper;
45 import android.content.DialogInterface;
46 import android.content.Intent;
47 import android.content.IntentFilter;
48 import android.content.IntentSender;
49 import android.content.SharedPreferences;
50 import android.content.pm.ActivityInfo;
51 import android.content.pm.ApplicationInfo;
52 import android.content.pm.PackageManager;
53 import android.content.pm.PackageManager.NameNotFoundException;
54 import android.content.res.Configuration;
55 import android.database.sqlite.SQLiteDatabase;
56 import android.graphics.Bitmap;
57 import android.graphics.Canvas;
58 import android.graphics.Color;
59 import android.graphics.PorterDuff;
60 import android.graphics.Rect;
61 import android.graphics.drawable.AnimationDrawable;
62 import android.graphics.drawable.ColorDrawable;
63 import android.graphics.drawable.Drawable;
64 import android.net.Uri;
65 import android.os.AsyncTask;
66 import android.os.Build;
67 import android.os.Bundle;
68 import android.os.Environment;
69 import android.os.Handler;
70 import android.os.Message;
71 import android.os.StrictMode;
72 import android.os.SystemClock;
73 import android.os.SystemProperties;
74 import android.os.UserHandle;
75 import android.provider.Settings;
76 import android.support.v4.app.ActivityCompat;
77 import android.support.v4.content.ContextCompat;
78 import android.text.Selection;
79 import android.text.SpannableStringBuilder;
80 import android.text.TextUtils;
81 import android.text.method.TextKeyListener;
82 import android.util.Log;
83 import android.view.Display;
84 import android.view.HapticFeedbackConstants;
85 import android.view.KeyEvent;
86 import android.view.LayoutInflater;
87 import android.view.Menu;
88 import android.view.MotionEvent;
89 import android.view.Surface;
90 import android.view.View;
91 import android.view.View.OnClickListener;
92 import android.view.View.OnLongClickListener;
93 import android.view.ViewGroup;
94 import android.view.ViewStub;
95 import android.view.ViewTreeObserver;
96 import android.view.Window;
97 import android.view.WindowManager;
98 import android.view.accessibility.AccessibilityEvent;
99 import android.view.animation.OvershootInterpolator;
100 import android.view.inputmethod.InputMethodManager;
101 import android.widget.Advanceable;
102 import android.widget.ImageView;
103 import android.widget.TextView;
104 import android.widget.Toast;
106 import com.android.launcher3.DropTarget.DragObject;
107 import com.android.launcher3.PagedView.PageSwitchListener;
108 import com.android.launcher3.allapps.AllAppsContainerView;
109 import com.android.launcher3.compat.AppWidgetManagerCompat;
110 import com.android.launcher3.compat.LauncherActivityInfoCompat;
111 import com.android.launcher3.compat.LauncherAppsCompat;
112 import com.android.launcher3.compat.UserHandleCompat;
113 import com.android.launcher3.compat.UserManagerCompat;
114 import com.android.launcher3.list.SettingsPinnedHeaderAdapter;
115 import com.android.launcher3.model.WidgetsModel;
116 import com.android.launcher3.settings.SettingsProvider;
117 import com.android.launcher3.stats.LauncherStats;
118 import com.android.launcher3.util.ComponentKey;
119 import com.android.launcher3.util.LongArrayMap;
120 import com.android.launcher3.util.TestingUtils;
121 import com.android.launcher3.util.Thunk;
122 import com.android.launcher3.widget.PendingAddWidgetInfo;
123 import com.android.launcher3.widget.WidgetHostViewLoader;
124 import com.android.launcher3.widget.WidgetsContainerView;
127 import java.io.FileDescriptor;
128 import java.io.FileInputStream;
129 import java.io.FileNotFoundException;
130 import java.io.FileOutputStream;
131 import java.io.IOException;
132 import java.io.PrintWriter;
133 import java.nio.channels.FileChannel;
134 import java.text.DateFormat;
135 import java.text.SimpleDateFormat;
136 import java.util.ArrayList;
137 import java.util.Collection;
138 import java.util.Date;
139 import java.util.HashMap;
140 import java.util.HashSet;
141 import java.util.List;
142 import java.util.concurrent.atomic.AtomicInteger;
145 * Default launcher application.
147 public class Launcher extends Activity
148 implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
149 View.OnTouchListener, PageSwitchListener, LauncherProviderChangeListener {
150 static final String TAG = "Launcher";
151 static final boolean LOGD = false;
153 static final boolean PROFILE_STARTUP = false;
154 static final boolean DEBUG_WIDGETS = false;
155 static final boolean DEBUG_STRICT_MODE = false;
156 static final boolean DEBUG_RESUME_TIME = false;
157 static final boolean DEBUG_DUMP_LOG = false;
159 static final boolean ENABLE_DEBUG_INTENTS = false; // allow DebugIntents to run
161 private static final int REQUEST_CREATE_SHORTCUT = 1;
162 private static final int REQUEST_CREATE_APPWIDGET = 5;
163 private static final int REQUEST_PICK_APPWIDGET = 9;
164 private static final int REQUEST_PICK_WALLPAPER = 10;
166 private static final int REQUEST_BIND_APPWIDGET = 11;
167 private static final int REQUEST_RECONFIGURE_APPWIDGET = 12;
169 private static final int REQUEST_PERMISSION_CALL_PHONE = 13;
171 public static final int REQUEST_OPEN_PROTECTED_FOLDER = 14;
172 public static final int REQUEST_PROTECT_FOLDER = 15;
173 public static final int REQUEST_UNPROTECT_FOLDER = 16;
175 private static final int WORKSPACE_BACKGROUND_GRADIENT = 0;
176 private static final int WORKSPACE_BACKGROUND_TRANSPARENT = 1;
177 private static final int WORKSPACE_BACKGROUND_BLACK = 2;
179 private static final float BOUNCE_ANIMATION_TENSION = 1.3f;
182 public static final String LONGPRESS_CHANGE = "wallpaper_changed_by_longpress";
186 * IntentStarter uses request codes starting with this. This must be greater than all activity
187 * request codes used internally.
189 protected static final int REQUEST_LAST = 100;
191 static final int SCREEN_COUNT = 5;
193 // To turn on these properties, type
194 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
195 static final String DUMP_STATE_PROPERTY = "launcher_dump_state";
197 // The Intent extra that defines whether to ignore the launch animation
198 static final String INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION =
199 "com.android.launcher3.intent.extra.shortcut.INGORE_LAUNCH_ANIMATION";
202 private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
204 private static final String RUNTIME_STATE = "launcher.state";
206 private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container";
208 private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
210 private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x";
212 private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y";
214 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_span_x";
216 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_span_y";
218 private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_INFO = "launcher.add_widget_info";
220 private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_ID = "launcher.add_widget_id";
222 private static final String RUNTIME_STATE_VIEW_IDS = "launcher.view_ids";
224 static final String INTRO_SCREEN_DISMISSED = "launcher.intro_screen_dismissed";
225 static final String FIRST_RUN_ACTIVITY_DISPLAYED = "launcher.first_run_activity_displayed";
227 static final String FIRST_LOAD_COMPLETE = "launcher.first_load_complete";
228 static final String ACTION_FIRST_LOAD_COMPLETE =
229 "com.android.launcher3.action.FIRST_LOAD_COMPLETE";
231 private static final String QSB_WIDGET_ID = "qsb_widget_id";
232 private static final String QSB_WIDGET_PROVIDER = "qsb_widget_provider";
233 private static final String PROPERTY_SHOW_TREB_HIDDEN =
234 "persist.data.show_treb_hidden";
235 private final int PERMISSION_REQUEST_CODE_EXPORT_DB = 1;
237 public static final String USER_HAS_MIGRATED = "launcher.user_migrated_from_old_data";
239 /** The different states that Launcher can be in. */
240 enum State { NONE, WORKSPACE, APPS, APPS_SPRING_LOADED, WIDGETS, WIDGETS_SPRING_LOADED }
242 @Thunk State mState = State.WORKSPACE;
243 @Thunk LauncherStateTransitionAnimation mStateTransitionAnimation;
245 private boolean mIsSafeModeEnabled;
247 LauncherOverlayCallbacks mLauncherOverlayCallbacks = new LauncherOverlayCallbacksImpl();
248 LauncherOverlay mLauncherOverlay;
249 InsettableFrameLayout mLauncherOverlayContainer;
251 static final int APPWIDGET_HOST_ID = 1024;
252 public static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300;
253 private static final int ON_ACTIVITY_RESULT_ANIMATION_DELAY = 500;
254 private static final int ACTIVITY_START_DELAY = 1000;
256 private HashMap<Integer, Integer> mItemIdToViewId = new HashMap<Integer, Integer>();
257 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
259 // How long to wait before the new-shortcut animation automatically pans the workspace
260 private static int NEW_APPS_PAGE_MOVE_DELAY = 500;
261 private static int NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS = 5;
262 @Thunk static int NEW_APPS_ANIMATION_DELAY = 500;
264 private final BroadcastReceiver mCloseSystemDialogsReceiver
265 = new CloseSystemDialogsIntentReceiver();
267 @Thunk final NetworkConnectionReceiver mConnectionReceiver = new NetworkConnectionReceiver();
268 @Thunk final DeviceUnlockedReceiver mDeviceUnlockedReceiver = new DeviceUnlockedReceiver();
270 private LayoutInflater mInflater;
272 @Thunk Workspace mWorkspace;
273 private View mLauncherView;
274 private View mPageIndicators;
275 @Thunk DragLayer mDragLayer;
276 private DragController mDragController;
277 private DynamicGridSizeFragment mDynamicGridSizeFragment;
278 private boolean mIsHiddenMenuOptionEnabled;
280 public View mWeightWatcher;
282 protected static RemoteFolderManager sRemoteFolderManager;
284 private AppWidgetManagerCompat mAppWidgetManager;
285 private LauncherAppWidgetHost mAppWidgetHost;
287 @Thunk ItemInfo mPendingAddInfo = new ItemInfo();
288 private LauncherAppWidgetProviderInfo mPendingAddWidgetInfo;
289 private int mPendingAddWidgetId = -1;
291 private int[] mTmpAddItemCellCoordinates = new int[2];
293 protected FolderIcon mHiddenFolderIcon;
294 private boolean mHiddenFolderLockStateChanged = false;
295 private boolean mHiddenFolderAuth = false;
297 @Thunk Hotseat mHotseat;
298 private VerticalSlidingPanel mOverviewPanel;
299 private View mDarkPanel;
300 OverviewSettingsPanel mOverviewSettingsPanel;
302 private View mAllAppsButton;
303 private View mWidgetsButton;
305 private SearchDropTargetBar mSearchDropTargetBar;
307 // Main container view for the all apps screen.
308 @Thunk AllAppsContainerView mAppsView;
310 // Main container view and the model for the widget tray screen.
311 @Thunk WidgetsContainerView mWidgetsView;
312 @Thunk WidgetsModel mWidgetsModel;
314 private boolean mAutoAdvanceRunning = false;
315 private AppWidgetHostView mQsb;
317 private Bundle mSavedState;
318 // We set the state in both onCreate and then onNewIntent in some cases, which causes both
319 // scroll issues (because the workspace may not have been measured yet) and extra work.
320 // Instead, just save the state that we need to restore Launcher to, and commit it in onResume.
321 private State mOnResumeState = State.NONE;
323 private SpannableStringBuilder mDefaultKeySsb = null;
325 @Thunk boolean mWorkspaceLoading = true;
327 private boolean mPaused = true;
328 private boolean mRestoring;
329 private boolean mWaitingForResult;
330 private boolean mOnResumeNeedsLoad;
332 private ArrayList<Runnable> mBindOnResumeCallbacks = new ArrayList<Runnable>();
333 private ArrayList<Runnable> mOnResumeCallbacks = new ArrayList<Runnable>();
335 private Bundle mSavedInstanceState;
337 protected LauncherModel mModel;
338 private IconCache mIconCache;
339 @Thunk boolean mUserPresent = true;
340 private boolean mVisible = false;
341 private boolean mHasFocus = false;
342 private boolean mAttached = false;
344 private File mExportedLauncherDB = null;
346 private LauncherClings mClings;
348 private static LongArrayMap<FolderInfo> sFolders = new LongArrayMap<>();
350 private View.OnTouchListener mHapticFeedbackTouchListener;
352 // Related to the auto-advancing of widgets
353 private final int ADVANCE_MSG = 1;
354 private final int mAdvanceInterval = 20000;
355 private final int mAdvanceStagger = 250;
356 private long mAutoAdvanceSentTime;
357 private long mAutoAdvanceTimeLeft = -1;
358 @Thunk HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance =
359 new HashMap<View, AppWidgetProviderInfo>();
361 // Determines how long to wait after a rotation before restoring the screen orientation to
362 // match the sensor state.
363 private final int mRestoreScreenOrientationDelay = 500;
365 @Thunk Drawable mWorkspaceBackgroundDrawable;
367 private final ArrayList<Integer> mSynchronouslyBoundPages = new ArrayList<Integer>();
368 private static final boolean DISABLE_SYNCHRONOUS_BINDING_CURRENT_PAGE = false;
370 static final ArrayList<String> sDumpLogs = new ArrayList<String>();
371 static Date sDateStamp = new Date();
372 static DateFormat sDateFormat =
373 DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
374 static long sRunStart = System.currentTimeMillis();
375 static final String CORRUPTION_EMAIL_SENT_KEY = "corruptionEmailSent";
377 // We only want to get the SharedPreferences once since it does an FS stat each time we get
378 // it from the context.
379 private SharedPreferences mSharedPrefs;
381 // Holds the page that we need to animate to, and the icon views that we need to animate up
382 // when we scroll to that page on resume.
383 @Thunk ImageView mFolderIconImageView;
384 private Bitmap mFolderIconBitmap;
385 private Canvas mFolderIconCanvas;
386 private Rect mRectForFolderAnimation = new Rect();
388 private DeviceProfile mDeviceProfile;
390 private boolean mUseScrubber = true;
392 private boolean mIsDrawerSearchBarEnabled;
394 // This is set to the view that launched the activity that navigated the user away from
395 // launcher. Since there is no callback for when the activity has finished launching, enable
396 // the press state and keep this reference to reset the press state when we return to launcher.
397 BubbleTextView mWaitingForResume;
399 private long mDefaultScreenId;
401 public Animator.AnimatorListener mAnimatorListener = new Animator.AnimatorListener() {
403 public void onAnimationStart(Animator arg0) {}
405 public void onAnimationRepeat(Animator arg0) {}
407 public void onAnimationEnd(Animator arg0) {
408 mDarkPanel.setVisibility(View.GONE);
411 public void onAnimationCancel(Animator arg0) {}
414 Runnable mReloadLauncherRunnable = new Runnable() {
417 reloadLauncher(mWorkspace.getRestorePage(), true, false);
421 private BroadcastReceiver protectedAppsChangedReceiver = new BroadcastReceiver() {
423 public void onReceive(Context context, Intent intent) {
424 // Update the workspace
425 if (waitUntilResume(mReloadLauncherRunnable, true)) {
429 reloadLauncher(mWorkspace.getRestorePage(), true, false);
433 private BroadcastReceiver searchBarVisibilityChangedReceiver = new BroadcastReceiver() {
435 public void onReceive(Context context, Intent intent) {
436 // Update the workspace
437 if (waitUntilResume(mReloadLauncherRunnable, true)) {
441 reloadLauncher(mWorkspace.getRestorePage(), true, false);
446 private boolean mHideIconLabels;
448 protected static HashMap<String, CustomAppWidget> sCustomAppWidgets =
449 new HashMap<String, CustomAppWidget>();
452 if (TestingUtils.ENABLE_CUSTOM_WIDGET_TEST) {
453 TestingUtils.addDummyWidget(sCustomAppWidgets);
457 @Thunk Runnable mBuildLayersRunnable = new Runnable() {
459 if (mWorkspace != null) {
460 mWorkspace.buildPageHardwareLayers();
465 private static PendingAddArguments sPendingAddItem;
467 @Thunk static class PendingAddArguments {
477 private Stats mStats;
478 FocusIndicatorView mFocusHandler;
479 private boolean mRotationEnabled = false;
481 @Thunk void setOrientation() {
482 if (mRotationEnabled) {
483 unlockScreenOrientation(true);
485 setRequestedOrientation(
486 ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
490 private Runnable mUpdateOrientationRunnable = new Runnable() {
496 private void requestWriteExternalPermission(){
497 ActivityCompat.requestPermissions(
499 new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
500 PERMISSION_REQUEST_CODE_EXPORT_DB
504 private boolean checkWriteExternalPermission(){
505 int result = ContextCompat.checkSelfPermission(
507 Manifest.permission.WRITE_EXTERNAL_STORAGE
509 if (result == PackageManager.PERMISSION_GRANTED) {
516 // returns true if mIsHiddenMenuOptionEnabled was updated else
518 private boolean updateHiddenMenuOption() {
519 boolean option = SystemProperties.getBoolean(
520 PROPERTY_SHOW_TREB_HIDDEN,
523 if ( option == mIsHiddenMenuOptionEnabled ) {
526 mIsHiddenMenuOptionEnabled = option;
531 private void deleteExportedLauncerDB() {
532 if ( mExportedLauncherDB != null && mExportedLauncherDB.exists() ) {
533 mExportedLauncherDB.delete();
535 mExportedLauncherDB = null;
538 private File exportFile(File inputFile, String outputPath) throws IOException {
539 File outputFolder = new File( outputPath );
540 if( !outputFolder.exists() ) {
541 outputFolder.mkdir();
544 String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
545 File outputFile = new File(
546 outputPath + File.separator + "launcher_" + timeStamp + ".db"
548 FileChannel inChannel = null;
549 FileChannel outChannel = null;
552 inChannel = new FileInputStream(inputFile).getChannel();
553 outChannel = new FileOutputStream(outputFile).getChannel();
554 } catch (FileNotFoundException e) {
559 inChannel.transferTo(0, inChannel.size(), outChannel);
561 if (inChannel != null)
563 if (outChannel != null)
570 protected void onCreate(Bundle savedInstanceState) {
571 if (DEBUG_STRICT_MODE) {
572 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
575 .detectNetwork() // or .detectAll() for all detectable problems
578 StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
579 .detectLeakedSqlLiteObjects()
580 .detectLeakedClosableObjects()
586 if (mLauncherCallbacks != null) {
587 mLauncherCallbacks.preOnCreate();
590 super.onCreate(savedInstanceState);
592 LauncherAppState.setApplicationContext(getApplicationContext());
593 LauncherAppState app = LauncherAppState.getInstance();
595 initializeDeviceProfile(app);
597 mSharedPrefs = getSharedPreferences(LauncherAppState.getSharedPreferencesKey(),
598 Context.MODE_PRIVATE);
599 mIsSafeModeEnabled = getPackageManager().isSafeMode();
601 mDragController = new DragController(this);
602 mInflater = getLayoutInflater();
603 mStateTransitionAnimation = new LauncherStateTransitionAnimation(this);
605 mStats = new Stats(this);
607 mAppWidgetManager = AppWidgetManagerCompat.getInstance(this);
609 mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
611 if (sRemoteFolderManager == null) {
612 sRemoteFolderManager = new RemoteFolderManager(this);
614 sRemoteFolderManager.onRecreateLauncher(this);
617 // If we are getting an onCreate, we can actually preempt onResume and unset mPaused here,
618 // this also ensures that any synchronous binding below doesn't re-trigger another
619 // LauncherModel load.
622 if (PROFILE_STARTUP) {
623 android.os.Debug.startMethodTracing(
624 Environment.getExternalStorageDirectory() + "/launcher");
627 setContentView(R.layout.launcher);
629 updateHiddenMenuOption();
631 mDeviceProfile.layout(this);
635 mSavedState = savedInstanceState;
636 restoreState(mSavedState);
638 if (PROFILE_STARTUP) {
639 android.os.Debug.stopMethodTracing();
643 if (DISABLE_SYNCHRONOUS_BINDING_CURRENT_PAGE) {
644 // If the user leaves launcher, then we should just load items asynchronously when
646 mModel.startLoader(PagedView.INVALID_RESTORE_PAGE);
648 // We only load the page synchronously if the user rotates (or triggers a
649 // configuration change) while launcher is in the foreground
650 mModel.startLoader(mWorkspace.getRestorePage());
654 // For handling default keys
655 mDefaultKeySsb = new SpannableStringBuilder();
656 Selection.setSelection(mDefaultKeySsb, 0);
658 IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
659 registerReceiver(mCloseSystemDialogsReceiver, filter);
661 filter = new IntentFilter(NetworkConnectionReceiver.INTENT_ACTION);
662 registerReceiver(mConnectionReceiver, filter);
664 filter = new IntentFilter(DeviceUnlockedReceiver.INTENT_ACTION);
665 registerReceiver(mDeviceUnlockedReceiver, filter);
667 mRotationEnabled = Utilities.isRotationAllowedForDevice(getApplicationContext());
668 // In case we are on a device with locked rotation, we should look at preferences to check
669 // if the user has specifically allowed rotation.
670 if (!mRotationEnabled) {
671 mRotationEnabled = Utilities.isAllowRotationPrefEnabled(getApplicationContext(), false);
674 // On large interfaces, or on devices that a user has specifically enabled screen rotation,
675 // we want the screen to auto-rotate based on the current orientation
678 if (mLauncherCallbacks != null) {
679 mLauncherCallbacks.onCreate(savedInstanceState);
680 if (mLauncherCallbacks.hasLauncherOverlay()) {
681 ViewStub stub = (ViewStub) findViewById(R.id.launcher_overlay_stub);
682 mLauncherOverlayContainer = (InsettableFrameLayout) stub.inflate();
683 mLauncherOverlay = mLauncherCallbacks.setLauncherOverlayView(
684 mLauncherOverlayContainer, mLauncherOverlayCallbacks);
685 mWorkspace.setLauncherOverlay(mLauncherOverlay);
689 if (shouldShowIntroScreen()) {
692 showFirstRunActivity();
693 showFirstRunClings();
696 IntentFilter protectedAppsFilter = new IntentFilter(
697 cyanogenmod.content.Intent.ACTION_PROTECTED_CHANGED);
698 registerReceiver(protectedAppsChangedReceiver, protectedAppsFilter,
699 cyanogenmod.platform.Manifest.permission.PROTECTED_APP, null);
701 IntentFilter searchBarVisibilityFilter = new IntentFilter(
702 SettingsPinnedHeaderAdapter.ACTION_SEARCH_BAR_VISIBILITY_CHANGED);
703 registerReceiver(searchBarVisibilityChangedReceiver, searchBarVisibilityFilter);
706 public void checkPermissionsAndExportDBFile(){
707 if( checkWriteExternalPermission() == false) {
708 requestWriteExternalPermission();
714 public void exportDBFile() {
715 ContextWrapper c = new ContextWrapper(this);
716 File dbFile = c.getDatabasePath("launcher.db");
718 deleteExportedLauncerDB();
719 mExportedLauncherDB = exportFile(
721 Environment.getExternalStorageDirectory().getAbsolutePath()
723 } catch (IOException e) {
726 getString(R.string.export_db_could_not),
732 private final int EMAIL_DB_FILE_CODE = 101;
733 public void emailExportedFile() {
734 if( mExportedLauncherDB == null ) {
737 Uri path = Uri.fromFile(mExportedLauncherDB);
738 Intent emailIntent = new Intent(Intent.ACTION_SEND);
739 emailIntent.setType("vnd.android.cursor.dir/email");
740 emailIntent.putExtra(Intent.EXTRA_STREAM, path);
741 emailIntent.putExtra(
742 Intent.EXTRA_SUBJECT,
743 getString(R.string.export_db_email_subject)
745 startActivityForResult(emailIntent , EMAIL_DB_FILE_CODE);
749 public void onSettingsChanged(String settings, boolean value) {
750 if (SettingsProvider.SETTINGS_UI_ALLOW_ROTATION.equals(settings)) {
751 mRotationEnabled = value;
752 if (!waitUntilResume(mUpdateOrientationRunnable, true)) {
753 mUpdateOrientationRunnable.run();
758 private LauncherCallbacks mLauncherCallbacks;
760 public void onPostCreate(Bundle savedInstanceState) {
761 super.onPostCreate(savedInstanceState);
762 if (mLauncherCallbacks != null) {
763 mLauncherCallbacks.onPostCreate(savedInstanceState);
767 public boolean setLauncherCallbacks(LauncherCallbacks callbacks) {
768 mLauncherCallbacks = callbacks;
769 mLauncherCallbacks.setLauncherSearchCallback(new Launcher.LauncherSearchCallbacks() {
770 private boolean mWorkspaceImportanceStored = false;
771 private boolean mHotseatImportanceStored = false;
772 private int mWorkspaceImportanceForAccessibility =
773 View.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
774 private int mHotseatImportanceForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
777 public void onSearchOverlayOpened() {
778 if (mWorkspaceImportanceStored || mHotseatImportanceStored) {
781 // The underlying workspace and hotseat are temporarily suppressed by the search
782 // overlay. So they sholudn't be accessible.
783 if (mWorkspace != null) {
784 mWorkspaceImportanceForAccessibility =
785 mWorkspace.getImportantForAccessibility();
786 mWorkspace.setImportantForAccessibility(
787 View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
788 mWorkspaceImportanceStored = true;
790 if (mHotseat != null) {
791 mHotseatImportanceForAccessibility = mHotseat.getImportantForAccessibility();
792 mHotseat.setImportantForAccessibility(
793 View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
794 mHotseatImportanceStored = true;
799 public void onSearchOverlayClosed() {
800 if (mWorkspaceImportanceStored && mWorkspace != null) {
801 mWorkspace.setImportantForAccessibility(mWorkspaceImportanceForAccessibility);
803 if (mHotseatImportanceStored && mHotseat != null) {
804 mHotseat.setImportantForAccessibility(mHotseatImportanceForAccessibility);
806 mWorkspaceImportanceStored = false;
807 mHotseatImportanceStored = false;
814 public void onLauncherProviderChange() {
815 if (mLauncherCallbacks != null) {
816 mLauncherCallbacks.onLauncherProviderChange();
821 * Updates the bounds of all the overlays to match the new fixed bounds.
823 public void updateOverlayBounds(Rect newBounds) {
824 mAppsView.setSearchBarBounds(newBounds);
825 mWidgetsView.setSearchBarBounds(newBounds);
828 /** To be overridden by subclasses to hint to Launcher that we have custom content */
829 protected boolean hasCustomContentToLeft() {
830 if (mLauncherCallbacks != null) {
831 return mLauncherCallbacks.hasCustomContentToLeft();
837 * To be overridden by subclasses to populate the custom content container and call
838 * {@link #addToCustomContentPage}. This will only be invoked if
839 * {@link #hasCustomContentToLeft()} is {@code true}.
841 protected void populateCustomContentContainer() {
842 if (mLauncherCallbacks != null) {
843 mLauncherCallbacks.populateCustomContentContainer();
848 * Invoked by subclasses to signal a change to the {@link #addCustomContentToLeft} value to
849 * ensure the custom content page is added or removed if necessary.
851 protected void invalidateHasCustomContentToLeft() {
852 if (mWorkspace == null || mWorkspace.getScreenOrder().isEmpty()) {
853 // Not bound yet, wait for bindScreens to be called.
857 if (!mWorkspace.hasCustomContent() && hasCustomContentToLeft()) {
858 // Create the custom content page and call the subclass to populate it.
859 mWorkspace.createCustomContentContainer();
860 populateCustomContentContainer();
861 } else if (mWorkspace.hasCustomContent() && !hasCustomContentToLeft()) {
862 mWorkspace.removeCustomContentPage();
866 public Stats getStats() {
870 public LayoutInflater getInflater() {
874 public boolean isDraggingEnabled() {
875 // We prevent dragging when we are loading the workspace as it is possible to pick up a view
876 // that is subsequently removed from the workspace in startBinding().
877 return !isWorkspaceLoading();
880 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
881 public static int generateViewId() {
882 if (Utilities.ATLEAST_JB_MR1) {
883 return View.generateViewId();
885 // View.generateViewId() is not available. The following fallback logic is a copy
886 // of its implementation.
888 final int result = sNextGeneratedId.get();
889 // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
890 int newValue = result + 1;
891 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
892 if (sNextGeneratedId.compareAndSet(result, newValue)) {
899 public int getViewIdForItem(ItemInfo info) {
900 // This cast is safe given the > 2B range for int.
901 int itemId = (int) info.id;
902 if (mItemIdToViewId.containsKey(itemId)) {
903 return mItemIdToViewId.get(itemId);
905 int viewId = generateViewId();
906 mItemIdToViewId.put(itemId, viewId);
911 * Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have
912 * a configuration step, this allows the proper animations to run after other transitions.
914 private long completeAdd(PendingAddArguments args) {
915 long screenId = args.screenId;
916 if (args.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
917 // When the screen id represents an actual screen (as opposed to a rank) we make sure
918 // that the drop page actually exists.
919 screenId = ensurePendingDropLayoutExists(args.screenId);
922 switch (args.requestCode) {
923 case REQUEST_CREATE_SHORTCUT:
924 completeAddShortcut(args.intent, args.container, screenId, args.cellX,
927 case REQUEST_CREATE_APPWIDGET:
928 completeAddAppWidget(args.appWidgetId, args.container, screenId, null, null);
930 case REQUEST_RECONFIGURE_APPWIDGET:
931 completeRestoreAppWidget(args.appWidgetId);
934 // Before adding this resetAddInfo(), after a shortcut was added to a workspace screen,
935 // if you turned the screen off and then back while in All Apps, Launcher would not
936 // return to the workspace. Clearing mAddInfo.container here fixes this issue
941 private void handleActivityResult(
942 final int requestCode, final int resultCode, final Intent data) {
943 // Reset the startActivity waiting flag
944 setWaitingForResult(false);
945 final int pendingAddWidgetId = mPendingAddWidgetId;
946 mPendingAddWidgetId = -1;
948 Runnable exitSpringLoaded = new Runnable() {
951 exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED),
952 EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
956 if (requestCode == REQUEST_BIND_APPWIDGET) {
957 // This is called only if the user did not previously have permissions to bind widgets
958 final int appWidgetId = data != null ?
959 data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
960 if (resultCode == RESULT_CANCELED) {
961 completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
962 mWorkspace.removeExtraEmptyScreenDelayed(true, exitSpringLoaded,
963 ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
964 } else if (resultCode == RESULT_OK) {
965 addAppWidgetImpl(appWidgetId, mPendingAddInfo, null,
966 mPendingAddWidgetInfo, ON_ACTIVITY_RESULT_ANIMATION_DELAY);
968 // When the user has granted permission to bind widgets, we should check to see if
969 // we can inflate the default search bar widget.
971 showWorkspace(false);
974 } else if (requestCode == REQUEST_PICK_WALLPAPER) {
975 if (resultCode == RESULT_OK && mWorkspace.isInOverviewMode()) {
976 showWorkspace(false);
979 } else if (requestCode == REQUEST_OPEN_PROTECTED_FOLDER) {
980 mHiddenFolderAuth = resultCode == RESULT_OK;
981 if (mHiddenFolderIcon != null && mHiddenFolderAuth) {
982 openFolder(mHiddenFolderIcon, null);
984 mHiddenFolderAuth = false;
987 } else if (requestCode == REQUEST_PROTECT_FOLDER) {
988 mHiddenFolderAuth = resultCode == RESULT_OK;
989 if (mHiddenFolderIcon != null && mHiddenFolderAuth) {
990 mHiddenFolderIcon.getFolder().saveHiddenFolderState(true);
991 mHiddenFolderLockStateChanged = true;
993 mHiddenFolderAuth = false;
995 } else if (requestCode == REQUEST_UNPROTECT_FOLDER) {
996 mHiddenFolderAuth = resultCode == RESULT_OK;
997 if (mHiddenFolderIcon != null && mHiddenFolderAuth) {
998 mHiddenFolderIcon.getFolder().saveHiddenFolderState(false);
999 mHiddenFolderLockStateChanged = true;
1001 mHiddenFolderAuth = false;
1005 boolean isWidgetDrop = (requestCode == REQUEST_PICK_APPWIDGET ||
1006 requestCode == REQUEST_CREATE_APPWIDGET);
1008 final boolean workspaceLocked = isWorkspaceLocked();
1009 // We have special handling for widgets
1011 final int appWidgetId;
1012 int widgetId = data != null ? data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1)
1015 appWidgetId = pendingAddWidgetId;
1017 appWidgetId = widgetId;
1021 if (appWidgetId < 0 || resultCode == RESULT_CANCELED) {
1022 Log.e(TAG, "Error: appWidgetId (EXTRA_APPWIDGET_ID) was not " +
1023 "returned from the widget configuration activity.");
1024 result = RESULT_CANCELED;
1025 completeTwoStageWidgetDrop(result, appWidgetId);
1026 final Runnable onComplete = new Runnable() {
1029 exitSpringLoadedDragModeDelayed(false, 0, null);
1032 if (workspaceLocked) {
1033 // No need to remove the empty screen if we're mid-binding, as the
1034 // the bind will not add the empty screen.
1035 mWorkspace.postDelayed(onComplete, ON_ACTIVITY_RESULT_ANIMATION_DELAY);
1037 mWorkspace.removeExtraEmptyScreenDelayed(true, onComplete,
1038 ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
1041 if (!workspaceLocked) {
1042 if (mPendingAddInfo.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
1043 // When the screen id represents an actual screen (as opposed to a rank)
1044 // we make sure that the drop page actually exists.
1045 mPendingAddInfo.screenId =
1046 ensurePendingDropLayoutExists(mPendingAddInfo.screenId);
1048 final CellLayout dropLayout = mWorkspace.getScreenWithId(mPendingAddInfo.screenId);
1050 dropLayout.setDropPending(true);
1051 final Runnable onComplete = new Runnable() {
1054 completeTwoStageWidgetDrop(resultCode, appWidgetId);
1055 dropLayout.setDropPending(false);
1058 mWorkspace.removeExtraEmptyScreenDelayed(true, onComplete,
1059 ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
1061 PendingAddArguments args = preparePendingAddArgs(requestCode, data, appWidgetId,
1063 sPendingAddItem = args;
1069 if (requestCode == REQUEST_RECONFIGURE_APPWIDGET) {
1070 if (resultCode == RESULT_OK) {
1071 // Update the widget view.
1072 PendingAddArguments args = preparePendingAddArgs(requestCode, data,
1073 pendingAddWidgetId, mPendingAddInfo);
1074 if (workspaceLocked) {
1075 sPendingAddItem = args;
1080 // Leave the widget in the pending state if the user canceled the configure.
1084 // The pattern used here is that a user PICKs a specific application,
1085 // which, depending on the target, might need to CREATE the actual target.
1087 // For example, the user would PICK_SHORTCUT for "Music playlist", and we
1088 // launch over to the Music app to actually CREATE_SHORTCUT.
1089 if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID) {
1090 final PendingAddArguments args = preparePendingAddArgs(requestCode, data, -1,
1092 if (isWorkspaceLocked()) {
1093 sPendingAddItem = args;
1096 mWorkspace.removeExtraEmptyScreenDelayed(true, exitSpringLoaded,
1097 ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
1099 } else if (resultCode == RESULT_CANCELED) {
1100 mWorkspace.removeExtraEmptyScreenDelayed(true, exitSpringLoaded,
1101 ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
1103 mDragLayer.clearAnimatedView();
1108 protected void onActivityResult(
1109 final int requestCode, final int resultCode, final Intent data) {
1110 if (requestCode == EMAIL_DB_FILE_CODE) {
1111 deleteExportedLauncerDB();
1113 handleActivityResult(requestCode, resultCode, data);
1115 if (mLauncherCallbacks != null) {
1116 mLauncherCallbacks.onActivityResult(requestCode, resultCode, data);
1120 /** @Override for MNC */
1121 public void onRequestPermissionsResult(int requestCode, String[] permissions,
1122 int[] grantResults) {
1123 if (requestCode == REQUEST_PERMISSION_CALL_PHONE && sPendingAddItem != null
1124 && sPendingAddItem.requestCode == REQUEST_PERMISSION_CALL_PHONE) {
1126 CellLayout layout = getCellLayout(sPendingAddItem.container, sPendingAddItem.screenId);
1127 if (layout != null) {
1128 v = layout.getChildAt(sPendingAddItem.cellX, sPendingAddItem.cellY);
1130 Intent intent = sPendingAddItem.intent;
1131 sPendingAddItem = null;
1132 if (grantResults.length > 0
1133 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
1134 startActivity(v, intent, null);
1136 // TODO: Show a snack bar with link to settings
1137 Toast.makeText(this, getString(R.string.msg_no_phone_permission,
1138 getString(R.string.app_name)), Toast.LENGTH_SHORT).show();
1140 } else if (requestCode == PERMISSION_REQUEST_CODE_EXPORT_DB) {
1141 if (grantResults.length > 0
1142 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
1144 emailExportedFile();
1148 getString(R.string.export_db_could_not) + ". " +
1149 getString(R.string.storage_permission_denied),
1154 if (mLauncherCallbacks != null) {
1155 mLauncherCallbacks.onRequestPermissionsResult(requestCode, permissions,
1160 private PendingAddArguments preparePendingAddArgs(int requestCode, Intent data, int
1161 appWidgetId, ItemInfo info) {
1162 PendingAddArguments args = new PendingAddArguments();
1163 args.requestCode = requestCode;
1165 args.container = info.container;
1166 args.screenId = info.screenId;
1167 args.cellX = info.cellX;
1168 args.cellY = info.cellY;
1169 args.appWidgetId = appWidgetId;
1174 * Check to see if a given screen id exists. If not, create it at the end, return the new id.
1176 * @param screenId the screen id to check
1177 * @return the new screen, or screenId if it exists
1179 private long ensurePendingDropLayoutExists(long screenId) {
1180 CellLayout dropLayout =
1181 (CellLayout) mWorkspace.getScreenWithId(screenId);
1182 if (dropLayout == null) {
1183 // it's possible that the add screen was removed because it was
1184 // empty and a re-bind occurred
1185 mWorkspace.addExtraEmptyScreen();
1186 return mWorkspace.commitExtraEmptyScreen();
1192 @Thunk void completeTwoStageWidgetDrop(final int resultCode, final int appWidgetId) {
1193 CellLayout cellLayout =
1194 (CellLayout) mWorkspace.getScreenWithId(mPendingAddInfo.screenId);
1195 Runnable onCompleteRunnable = null;
1196 int animationType = 0;
1198 AppWidgetHostView boundWidget = null;
1199 if (resultCode == RESULT_OK) {
1200 animationType = Workspace.COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION;
1201 final AppWidgetHostView layout = mAppWidgetHost.createView(this, appWidgetId,
1202 mPendingAddWidgetInfo);
1203 boundWidget = layout;
1204 onCompleteRunnable = new Runnable() {
1207 completeAddAppWidget(appWidgetId, mPendingAddInfo.container,
1208 mPendingAddInfo.screenId, layout, null);
1209 exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED),
1210 EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
1213 } else if (resultCode == RESULT_CANCELED) {
1214 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
1215 animationType = Workspace.CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION;
1217 if (mDragLayer.getAnimatedView() != null) {
1218 mWorkspace.animateWidgetDrop(mPendingAddInfo, cellLayout,
1219 (DragView) mDragLayer.getAnimatedView(), onCompleteRunnable,
1220 animationType, boundWidget, true);
1221 } else if (onCompleteRunnable != null) {
1222 // The animated view may be null in the case of a rotation during widget configuration
1223 onCompleteRunnable.run();
1228 protected void onStop() {
1230 FirstFrameAnimatorHelper.setIsVisible(false);
1232 if (mLauncherCallbacks != null) {
1233 mLauncherCallbacks.onStop();
1238 protected void onStart() {
1240 FirstFrameAnimatorHelper.setIsVisible(true);
1242 if (mLauncherCallbacks != null) {
1243 mLauncherCallbacks.onStart();
1245 // If AppwidgetService failed to bind in onCreate, this will attempt binding again.
1246 onAppWidgetHostReset();
1250 protected void onResume() {
1252 if (DEBUG_RESUME_TIME) {
1253 startTime = System.currentTimeMillis();
1254 Log.v(TAG, "Launcher.onResume()");
1257 if (mLauncherCallbacks != null) {
1258 mLauncherCallbacks.preOnResume();
1263 // Restore the previous launcher state
1264 if (mOnResumeState == State.WORKSPACE) {
1265 showWorkspace(false);
1266 } else if (mOnResumeState == State.APPS) {
1267 boolean launchedFromApp = (mWaitingForResume != null);
1268 // Don't update the predicted apps if the user is returning to launcher in the apps
1269 // view after launching an app, as they may be depending on the UI to be static to
1270 // switch to another app, otherwise, if it was
1271 showAppsView(false /* animated */, false /* resetListToTop */,
1272 !launchedFromApp /* updatePredictedApps */, false /* focusSearchBar */);
1273 mWorkspace.setVisibility(View.INVISIBLE);
1274 } else if (mOnResumeState == State.WIDGETS) {
1275 showWidgetsView(false, false);
1277 mOnResumeState = State.NONE;
1279 // Background was set to gradient in onPause(), restore to transparent if in all apps.
1280 setWorkspaceBackground(mState == State.WORKSPACE ? WORKSPACE_BACKGROUND_GRADIENT
1281 : WORKSPACE_BACKGROUND_TRANSPARENT);
1284 if (mRestoring || mOnResumeNeedsLoad) {
1285 setWorkspaceLoading(true);
1287 // If we're starting binding all over again, clear any bind calls we'd postponed in
1288 // the past (see waitUntilResume) -- we don't need them since we're starting binding
1289 // from scratch again
1290 mBindOnResumeCallbacks.clear();
1292 mModel.startLoader(PagedView.INVALID_RESTORE_PAGE);
1294 mOnResumeNeedsLoad = false;
1296 if (mBindOnResumeCallbacks.size() > 0) {
1297 // We might have postponed some bind calls until onResume (see waitUntilResume) --
1298 // execute them here
1299 long startTimeCallbacks = 0;
1300 if (DEBUG_RESUME_TIME) {
1301 startTimeCallbacks = System.currentTimeMillis();
1304 for (int i = 0; i < mBindOnResumeCallbacks.size(); i++) {
1305 mBindOnResumeCallbacks.get(i).run();
1307 mBindOnResumeCallbacks.clear();
1308 if (DEBUG_RESUME_TIME) {
1309 Log.d(TAG, "Time spent processing callbacks in onResume: " +
1310 (System.currentTimeMillis() - startTimeCallbacks));
1313 if (mOnResumeCallbacks.size() > 0) {
1314 for (int i = 0; i < mOnResumeCallbacks.size(); i++) {
1315 mOnResumeCallbacks.get(i).run();
1317 mOnResumeCallbacks.clear();
1320 // Reset the pressed state of icons that were locked in the press state while activities
1322 if (mWaitingForResume != null) {
1323 // Resets the previous workspace icon press state
1324 mWaitingForResume.setStayPressed(false);
1327 // It is possible that widgets can receive updates while launcher is not in the foreground.
1328 // Consequently, the widgets will be inflated in the orientation of the foreground activity
1329 // (framework issue). On resuming, we ensure that any widgets are inflated for the current
1331 getWorkspace().reinflateWidgetsIfNecessary();
1332 reinflateQSBIfNecessary();
1334 if (DEBUG_RESUME_TIME) {
1335 Log.d(TAG, "Time spent in onResume: " + (System.currentTimeMillis() - startTime));
1338 if (mWorkspace.getCustomContentCallbacks() != null) {
1339 // If we are resuming and the custom content is the current page, we call onShow().
1340 // It is also poassible that onShow will instead be called slightly after first layout
1341 // if PagedView#setRestorePage was set to the custom content page in onCreate().
1342 if (mWorkspace.isOnOrMovingToCustomContent()) {
1343 mWorkspace.getCustomContentCallbacks().onShow(true);
1346 updateInteraction(Workspace.State.NORMAL, mWorkspace.getState());
1347 mWorkspace.onResume();
1349 if (!isWorkspaceLoading()) {
1350 // Process any items that were added while Launcher was away.
1351 InstallShortcutReceiver.disableAndFlushInstallQueue(this);
1354 if (mLauncherCallbacks != null) {
1355 mLauncherCallbacks.onResume();
1358 // Close out fragments
1359 Fragment gridFragment = getFragmentManager().findFragmentByTag(
1360 DynamicGridSizeFragment.DYNAMIC_GRID_SIZE_FRAGMENT);
1361 if (gridFragment != null) {
1362 ((DynamicGridSizeFragment) gridFragment).setSize();
1363 unlockScreenOrientation(true);
1365 if( updateHiddenMenuOption() && mOverviewSettingsPanel != null){
1366 mOverviewSettingsPanel.initializeAdapter();
1371 protected void onPause() {
1372 // Ensure that items added to Launcher are queued until Launcher returns
1373 InstallShortcutReceiver.enableInstallQueue();
1377 mDragController.cancelDrag();
1378 mDragController.resetLastGestureUpTime();
1380 // We call onHide() aggressively. The custom content callbacks should be able to
1381 // debounce excess onHide calls.
1382 if (mWorkspace.getCustomContentCallbacks() != null) {
1383 mWorkspace.getCustomContentCallbacks().onHide();
1386 if (mLauncherCallbacks != null) {
1387 mLauncherCallbacks.onPause();
1391 public interface CustomContentCallbacks {
1392 // Custom content is completely shown. {@code fromResume} indicates whether this was caused
1393 // by a onResume or by scrolling otherwise.
1394 public void onShow(boolean fromResume);
1396 // Custom content is completely hidden
1397 public void onHide();
1399 // Custom content scroll progress changed. From 0 (not showing) to 1 (fully showing).
1400 public void onScrollProgressChanged(float progress);
1402 // Indicates whether the user is allowed to scroll away from the custom content.
1403 boolean isScrollingAllowed();
1406 public interface LauncherOverlay {
1409 * Touch interaction leading to overscroll has begun
1411 public void onScrollInteractionBegin();
1414 * Touch interaction related to overscroll has ended
1416 public void onScrollInteractionEnd();
1419 * Scroll progress, between 0 and 100, when the user scrolls beyond the leftmost
1420 * screen (or in the case of RTL, the rightmost screen).
1422 public void onScrollChange(int progress, boolean rtl);
1425 * Screen has stopped scrolling
1427 public void onScrollSettled();
1430 * This method can be called by the Launcher in order to force the LauncherOverlay
1431 * to exit fully immersive mode.
1433 public void forceExitFullImmersion();
1436 public interface LauncherSearchCallbacks {
1438 * Called when the search overlay is shown.
1440 public void onSearchOverlayOpened();
1443 * Called when the search overlay is dismissed.
1445 public void onSearchOverlayClosed();
1448 public interface LauncherOverlayCallbacks {
1450 * This method indicates whether a call to {@link #enterFullImmersion()} will succeed,
1451 * however it doesn't modify any state within the launcher.
1453 public boolean canEnterFullImmersion();
1456 * Should be called to tell Launcher that the LauncherOverlay will take over interaction,
1457 * eg. by occupying the full screen and handling all touch events.
1459 * @return true if Launcher allows the LauncherOverlay to become fully immersive. In this
1460 * case, Launcher will modify any necessary state and assumes the overlay is
1461 * handling all interaction. If false, the LauncherOverlay should cancel any
1464 public boolean enterFullImmersion();
1467 * Must be called when exiting fully immersive mode. Indicates to Launcher that it has
1468 * full control over UI and state.
1470 public void exitFullImmersion();
1473 class LauncherOverlayCallbacksImpl implements LauncherOverlayCallbacks {
1476 public boolean canEnterFullImmersion() {
1477 return mState == State.WORKSPACE;
1481 public boolean enterFullImmersion() {
1482 if (mState == State.WORKSPACE) {
1483 // When fully immersed, disregard any touches which fall through.
1484 mDragLayer.setBlockTouch(true);
1491 public void exitFullImmersion() {
1492 mDragLayer.setBlockTouch(false);
1496 protected boolean hasSettings() {
1497 if (mLauncherCallbacks != null) {
1498 return mLauncherCallbacks.hasSettings();
1500 // On devices with a locked orientation, we will at least have the allow rotation
1502 return !Utilities.isRotationAllowedForDevice(this);
1506 public void addToCustomContentPage(View customContent,
1507 CustomContentCallbacks callbacks, String description) {
1508 mWorkspace.addToCustomContentPage(customContent, callbacks, description);
1511 // The custom content needs to offset its content to account for the QSB
1512 public int getTopOffsetForCustomContent() {
1513 return mWorkspace.getPaddingTop();
1517 public Object onRetainNonConfigurationInstance() {
1518 // Flag the loader to stop early before switching
1519 if (mModel.isCurrentCallbacks(this)) {
1520 mModel.stopLoader();
1522 //TODO(hyunyoungs): stop the widgets loader when there is a rotation.
1524 return Boolean.TRUE;
1527 // We can't hide the IME if it was forced open. So don't bother
1529 public void onWindowFocusChanged(boolean hasFocus) {
1530 super.onWindowFocusChanged(hasFocus);
1531 mHasFocus = hasFocus;
1533 if (mLauncherCallbacks != null) {
1534 mLauncherCallbacks.onWindowFocusChanged(hasFocus);
1538 private boolean acceptFilter() {
1539 final InputMethodManager inputManager = (InputMethodManager)
1540 getSystemService(Context.INPUT_METHOD_SERVICE);
1541 return !inputManager.isFullscreenMode();
1545 public boolean onKeyDown(int keyCode, KeyEvent event) {
1546 final int uniChar = event.getUnicodeChar();
1547 final boolean handled = super.onKeyDown(keyCode, event);
1548 final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar);
1549 if (!handled && acceptFilter() && isKeyNotWhitespace) {
1550 boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
1552 if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
1553 // something usable has been typed - start a search
1554 // the typed text will be retrieved and cleared by
1555 // showSearchDialog()
1556 // If there are multiple keystrokes before the search dialog takes focus,
1557 // onSearchRequested() will be called for every keystroke,
1558 // but it is idempotent, so it's fine.
1559 return onSearchRequested();
1563 // Eat the long press event so the keyboard doesn't come up.
1564 if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
1571 private String getTypedText() {
1572 return mDefaultKeySsb.toString();
1575 private void clearTypedText() {
1576 mDefaultKeySsb.clear();
1577 mDefaultKeySsb.clearSpans();
1578 Selection.setSelection(mDefaultKeySsb, 0);
1582 * Given the integer (ordinal) value of a State enum instance, convert it to a variable of type
1585 private static State intToState(int stateOrdinal) {
1586 State state = State.WORKSPACE;
1587 final State[] stateValues = State.values();
1588 for (int i = 0; i < stateValues.length; i++) {
1589 if (stateValues[i].ordinal() == stateOrdinal) {
1590 state = stateValues[i];
1598 * Restores the previous state, if it exists.
1600 * @param savedState The previous state.
1602 @SuppressWarnings("unchecked")
1603 private void restoreState(Bundle savedState) {
1604 if (savedState == null) {
1608 State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
1609 if (state == State.APPS || state == State.WIDGETS) {
1610 mOnResumeState = state;
1613 int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN,
1614 PagedView.INVALID_RESTORE_PAGE);
1615 if (currentScreen != PagedView.INVALID_RESTORE_PAGE) {
1616 mWorkspace.setRestorePage(currentScreen);
1619 final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
1620 final long pendingAddScreen = savedState.getLong(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
1622 if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
1623 mPendingAddInfo.container = pendingAddContainer;
1624 mPendingAddInfo.screenId = pendingAddScreen;
1625 mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
1626 mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
1627 mPendingAddInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
1628 mPendingAddInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
1629 AppWidgetProviderInfo info = savedState.getParcelable(
1630 RUNTIME_STATE_PENDING_ADD_WIDGET_INFO);
1631 mPendingAddWidgetInfo = info == null ?
1632 null : LauncherAppWidgetProviderInfo.fromProviderInfo(this, info);
1634 mPendingAddWidgetId = savedState.getInt(RUNTIME_STATE_PENDING_ADD_WIDGET_ID);
1635 setWaitingForResult(true);
1639 mItemIdToViewId = (HashMap<Integer, Integer>)
1640 savedState.getSerializable(RUNTIME_STATE_VIEW_IDS);
1644 * Finds all the views we need and configure them properly.
1646 private void setupViews() {
1647 final DragController dragController = mDragController;
1649 mLauncherView = findViewById(R.id.launcher);
1650 mFocusHandler = (FocusIndicatorView) findViewById(R.id.focus_indicator);
1651 mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
1652 mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
1653 mWorkspace.setPageSwitchListener(this);
1654 mPageIndicators = mDragLayer.findViewById(R.id.page_indicator);
1656 mLauncherView.setSystemUiVisibility(
1657 View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
1658 mWorkspaceBackgroundDrawable = getResources().getDrawable(R.drawable.workspace_bg);
1660 // Setup the drag layer
1661 mDragLayer.setup(this, dragController);
1663 // Setup the hotseat
1664 mHotseat = (Hotseat) findViewById(R.id.hotseat);
1665 if (mHotseat != null) {
1666 mHotseat.setOnLongClickListener(this);
1669 // Setup the overview panel
1670 mOverviewPanel = (VerticalSlidingPanel) findViewById(R.id.overview_panel);
1671 mOverviewSettingsPanel = new OverviewSettingsPanel(this);
1672 mOverviewSettingsPanel.initializeAdapter();
1674 mDarkPanel = mOverviewPanel.findViewById(R.id.dark_panel);
1676 mWidgetsButton = findViewById(R.id.widget_button);
1677 mWidgetsButton.setOnClickListener(new OnClickListener() {
1679 public void onClick(View arg0) {
1680 if (!mWorkspace.isSwitchingState()) {
1681 onClickAddWidgetButton(arg0);
1685 mWidgetsButton.setOnTouchListener(getHapticFeedbackTouchListener());
1687 View wallpaperButton = findViewById(R.id.wallpaper_button);
1688 wallpaperButton.setOnClickListener(new OnClickListener() {
1690 public void onClick(View arg0) {
1691 if (!mWorkspace.isSwitchingState()) {
1692 onClickWallpaperPicker(arg0);
1696 wallpaperButton.setOnTouchListener(getHapticFeedbackTouchListener());
1698 View settingsButton = findViewById(R.id.settings_button);
1699 if (hasSettings()) {
1700 settingsButton.setOnClickListener(new OnClickListener() {
1702 public void onClick(View arg0) {
1703 if (!mWorkspace.isSwitchingState()) {
1704 onClickSettingsButton(arg0);
1708 settingsButton.setOnTouchListener(getHapticFeedbackTouchListener());
1710 settingsButton.setVisibility(View.GONE);
1713 View defaultScreenButton = findViewById(R.id.default_screen_button);
1714 defaultScreenButton.setOnClickListener(new OnClickListener() {
1716 public void onClick(View arg0) {
1717 if (!mWorkspace.isSwitchingState()) {
1718 onClickDefaultScreenButton(arg0);
1722 defaultScreenButton.setOnTouchListener(getHapticFeedbackTouchListener());
1724 mOverviewPanel.setPanelSlideListener(new SettingsPanelSlideListener());
1725 mOverviewPanel.setEnableDragViewTouchEvents(true);
1727 View settingsPaneHeader = mOverviewPanel.findViewById(R.id.settings_pane_header);
1728 if (settingsPaneHeader != null) {
1729 mOverviewPanel.setDragView(settingsPaneHeader);
1730 settingsPaneHeader.setOnClickListener(new OnClickListener() {
1732 public void onClick(View v) {
1733 if (mOverviewPanel.isExpanded()) {
1734 mOverviewPanel.collapsePane();
1736 mOverviewPanel.expandPane();
1742 mOverviewPanel.setAlpha(0f);
1744 // Setup the workspace
1745 mWorkspace.setHapticFeedbackEnabled(false);
1746 mWorkspace.setOnLongClickListener(this);
1747 mWorkspace.setup(dragController);
1748 dragController.addDragListener(mWorkspace);
1750 // Get the search/delete bar
1751 mSearchDropTargetBar = (SearchDropTargetBar)
1752 mDragLayer.findViewById(R.id.search_drop_target_bar);
1754 // Setup Apps and Widgets
1755 mAppsView = (AllAppsContainerView) findViewById(R.id.apps_view);
1756 mWidgetsView = (WidgetsContainerView) findViewById(R.id.widgets_view);
1757 setupSearchBar(this);
1759 // Setup the drag controller (drop targets have to be added in reverse order in priority)
1760 dragController.setDragScoller(mWorkspace);
1761 dragController.setScrollView(mDragLayer);
1762 dragController.setMoveTarget(mWorkspace);
1763 dragController.addDropTarget(mWorkspace);
1764 if (mSearchDropTargetBar != null) {
1765 mSearchDropTargetBar.setup(this, dragController);
1766 mSearchDropTargetBar.setQsbSearchBar(getOrCreateQsbBar());
1769 if (TestingUtils.MEMORY_DUMP_ENABLED) {
1770 TestingUtils.addWeightWatcher(this);
1773 sRemoteFolderManager.onSetupViews();
1777 * Sets the all apps button. This method is called from {@link Hotseat}.
1779 public void setAllAppsButton(View allAppsButton) {
1780 mAllAppsButton = allAppsButton;
1783 public View getAllAppsButton() {
1784 return mAllAppsButton;
1787 public View getWidgetsButton() {
1788 return mWidgetsButton;
1792 * Creates a view representing a shortcut.
1794 * @param info The data structure describing the shortcut.
1796 View createShortcut(ShortcutInfo info) {
1797 return createShortcut((ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info);
1801 * Creates a view representing a shortcut inflated from the specified resource.
1803 * @param parent The group the shortcut belongs to.
1804 * @param info The data structure describing the shortcut.
1806 * @return A View inflated from layoutResId.
1808 public View createShortcut(ViewGroup parent, ShortcutInfo info) {
1809 BubbleTextView favorite = (BubbleTextView) mInflater.inflate(R.layout.app_icon,
1811 favorite.applyFromShortcutInfo(info, mIconCache);
1812 favorite.setTextVisibility(!mHideIconLabels);
1813 favorite.setCompoundDrawablePadding(mDeviceProfile.iconDrawablePaddingPx);
1814 favorite.setOnClickListener(this);
1815 favorite.setOnFocusChangeListener(mFocusHandler);
1820 * Add a shortcut to the workspace.
1822 * @param data The intent describing the shortcut.
1824 private void completeAddShortcut(Intent data, long container, long screenId, int cellX,
1826 int[] cellXY = mTmpAddItemCellCoordinates;
1827 int[] touchXY = mPendingAddInfo.dropPos;
1828 CellLayout layout = getCellLayout(container, screenId);
1830 ShortcutInfo info = InstallShortcutReceiver.fromShortcutIntent(this, data);
1834 final View view = createShortcut(info);
1836 boolean foundCellSpan = false;
1837 // First we check if we already know the exact location where we want to add this item.
1838 if (cellX >= 0 && cellY >= 0) {
1841 foundCellSpan = true;
1843 // If appropriate, either create a folder or add to an existing folder
1844 if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0,
1848 DragObject dragObject = new DragObject();
1849 dragObject.dragInfo = info;
1850 if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject,
1854 } else if (touchXY != null) {
1855 // when dragging and dropping, just find the closest free spot
1856 int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY);
1857 foundCellSpan = (result != null);
1859 foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
1862 if (!foundCellSpan) {
1863 showOutOfSpaceMessage(isHotseatLayout(layout));
1867 LauncherModel.addItemToDatabase(this, info, container, screenId, cellXY[0], cellXY[1]);
1870 mWorkspace.addInScreen(view, container, screenId, cellXY[0], cellXY[1], 1, 1,
1871 isWorkspaceLocked());
1876 * Add a widget to the workspace.
1878 * @param appWidgetId The app widget id
1880 @Thunk void completeAddAppWidget(int appWidgetId, long container, long screenId,
1881 AppWidgetHostView hostView, LauncherAppWidgetProviderInfo appWidgetInfo) {
1883 ItemInfo info = mPendingAddInfo;
1884 if (appWidgetInfo == null) {
1885 appWidgetInfo = LauncherAppWidgetProviderInfo.fromProviderInfo(this,
1886 mAppWidgetManager.getAppWidgetInfo(appWidgetId));
1889 if (appWidgetInfo.isCustomWidget) {
1890 appWidgetId = LauncherAppWidgetInfo.CUSTOM_WIDGET_ID;
1893 LauncherAppWidgetInfo launcherInfo;
1894 launcherInfo = new LauncherAppWidgetInfo(appWidgetId, appWidgetInfo.provider);
1895 launcherInfo.spanX = info.spanX;
1896 launcherInfo.spanY = info.spanY;
1897 launcherInfo.minSpanX = info.minSpanX;
1898 launcherInfo.minSpanY = info.minSpanY;
1899 launcherInfo.user = mAppWidgetManager.getUser(appWidgetInfo);
1901 LauncherModel.addItemToDatabase(this, launcherInfo,
1902 container, screenId, info.cellX, info.cellY);
1905 if (hostView == null) {
1906 // Perform actual inflation because we're live
1907 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId,
1910 // The AppWidgetHostView has already been inflated and instantiated
1911 launcherInfo.hostView = hostView;
1913 launcherInfo.hostView.setTag(launcherInfo);
1914 launcherInfo.hostView.setVisibility(View.VISIBLE);
1915 launcherInfo.notifyWidgetSizeChanged(this);
1917 mWorkspace.addInScreen(launcherInfo.hostView, container, screenId, info.cellX,
1918 info.cellY, launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
1920 addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
1925 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1927 public void onReceive(Context context, Intent intent) {
1928 final String action = intent.getAction();
1929 if (Intent.ACTION_SCREEN_OFF.equals(action)) {
1930 mUserPresent = false;
1931 mDragLayer.clearAllResizeFrames();
1932 updateAutoAdvanceState();
1934 // Reset AllApps to its initial state only if we are not in the middle of
1935 // processing a multi-step drop
1936 if (mAppsView != null && mWidgetsView != null &&
1937 mPendingAddInfo.container == ItemInfo.NO_ID) {
1938 showWorkspace(false);
1940 } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
1941 mUserPresent = true;
1942 updateAutoAdvanceState();
1943 } else if (ENABLE_DEBUG_INTENTS && DebugIntents.DELETE_DATABASE.equals(action)) {
1944 mModel.resetLoadedState(false, true);
1945 mModel.startLoader(PagedView.INVALID_RESTORE_PAGE,
1946 LauncherModel.LOADER_FLAG_CLEAR_WORKSPACE);
1947 } else if (ENABLE_DEBUG_INTENTS && DebugIntents.MIGRATE_DATABASE.equals(action)) {
1948 mModel.resetLoadedState(false, true);
1949 mModel.startLoader(PagedView.INVALID_RESTORE_PAGE,
1950 LauncherModel.LOADER_FLAG_CLEAR_WORKSPACE
1951 | LauncherModel.LOADER_FLAG_MIGRATE_SHORTCUTS);
1957 * Initializes the device profile based off of the launcher app state and screen orientation
1958 * @param app The launcher app state
1960 public void initializeDeviceProfile(LauncherAppState app) {
1961 // Load configuration-specific DeviceProfile
1962 mDeviceProfile = getResources().getConfiguration().orientation
1963 == Configuration.ORIENTATION_LANDSCAPE ?
1964 app.getInvariantDeviceProfile().landscapeProfile
1965 : app.getInvariantDeviceProfile().portraitProfile;
1967 mHideIconLabels = SettingsProvider.getBoolean(this,
1968 SettingsProvider.SETTINGS_UI_HOMESCREEN_HIDE_ICON_LABELS,
1969 R.bool.preferences_interface_homescreen_hide_icon_labels_default);
1970 mDefaultScreenId = SettingsProvider.getLongCustomDefault(this,
1971 SettingsProvider.SETTINGS_UI_HOMESCREEN_DEFAULT_SCREEN_ID,
1972 R.integer.preferences_interface_homescreen_id_default);
1974 mModel = app.setLauncher(this);
1975 mIconCache = app.getIconCache();
1980 * Re-initializes the device profile and layout and reloads the workspace and app drawer as
1982 * @param resizeGrid Indicates whether the grid should be resized
1983 * @param reloadAppDrawer Indicates whether the app drawer should be reloaded
1985 public void reloadLauncher(boolean resizeGrid, boolean reloadAppDrawer) {
1986 reloadLauncher(mWorkspace.getCurrentPage(), resizeGrid, reloadAppDrawer);
1990 * Re-initializes the device profile and layout and reloads the workspace and app drawer as
1992 * @param page The page to bind to
1993 * @param resizeGrid Indicates whether the grid should be resized
1994 * @param reloadAppDrawer Indicates whether the app drawer should be reloaded
1996 private void reloadLauncher(int page, boolean resizeGrid, boolean reloadAppDrawer)
1998 // Re-initialize device profile
1999 LauncherAppState app = LauncherAppState.getInstance();
2000 app.initInvariantDeviceProfile();
2001 initializeDeviceProfile(app);
2003 mDeviceProfile.layout(this);
2006 mModel.resetLoadedState(true, true);
2007 int flag = resizeGrid ? LauncherModel.LOADER_FLAG_RESIZE_GRID :
2008 LauncherModel.LOADER_FLAG_NONE;
2009 mModel.startLoader(page, flag);
2011 mWorkspace.updateCustomContentVisibility();
2013 mSearchDropTargetBar.setupQsb(this);
2015 if (reloadAppDrawer) {
2020 public void reloadAppDrawer() {
2021 List<AppInfo> addedApps = mAppsView.getApps();
2022 mDragLayer.removeView(mAppsView);
2023 mAppsView = (AllAppsContainerView)LayoutInflater
2024 .from(this).inflate(R.layout.all_apps, mDragLayer, false);
2025 mDragLayer.addView(mAppsView, mDragLayer.getChildCount() - 1);
2026 mAppsView.setVisibility(View.INVISIBLE);
2027 setupSearchBar(this);
2028 mAppsView.addApps(addedApps);
2029 tryAndUpdatePredictedApps();
2030 mAppsView.onReloadAppDrawer();
2031 sRemoteFolderManager.onReloadAppDrawer();
2034 public void reloadWidgetView() {
2035 WidgetsModel model = mWidgetsView.getWidgets();
2036 mDragLayer.removeView(mWidgetsView);
2037 mWidgetsView = (WidgetsContainerView)LayoutInflater
2038 .from(this).inflate(R.layout.widgets_view, mDragLayer, false);
2039 mDragLayer.addView(mWidgetsView, mDragLayer.getChildCount() - 2);
2040 mWidgetsView.setVisibility(View.INVISIBLE);
2041 if (model != null) {
2042 mWidgetsView.addWidgets(model);
2044 mWidgetsView.reset();
2048 * Replaces currently added fragments in the launcher layout with a
2049 * {@link DynamicGridSizeFragment}.
2051 public void onClickDynamicGridSizeButton() {
2052 FragmentManager fragmentManager = getFragmentManager();
2053 FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
2054 lockScreenOrientation();
2055 mDynamicGridSizeFragment = new DynamicGridSizeFragment();
2056 fragmentTransaction.replace(R.id.launcher, mDynamicGridSizeFragment,
2057 DynamicGridSizeFragment.DYNAMIC_GRID_SIZE_FRAGMENT);
2058 fragmentTransaction.commit();
2062 * If the new grid size is different from the current grid size, the launcher will be reloaded
2063 * and the overview settings panel updated with the new grid size value.
2064 * @param size The new grid size to set the workspace to.
2066 public void setDynamicGridSize(InvariantDeviceProfile.GridSize size) {
2067 if (size == null) return;
2069 int gridSize = SettingsProvider.getIntCustomDefault(this,
2070 SettingsProvider.SETTINGS_UI_DYNAMIC_GRID_SIZE, 0);
2071 boolean customValuesChanged = false;
2072 if (gridSize == size.getValue() && size == InvariantDeviceProfile.GridSize.Custom) {
2073 int tempRows = SettingsProvider.getIntCustomDefault(this,
2074 SettingsProvider.SETTINGS_UI_HOMESCREEN_ROWS, mDeviceProfile.inv.numRows);
2075 int tempColumns = SettingsProvider.getIntCustomDefault(this,
2076 SettingsProvider.SETTINGS_UI_HOMESCREEN_COLUMNS, mDeviceProfile.inv.numColumns);
2077 if (tempColumns != mDeviceProfile.inv.numColumns ||
2078 tempRows != mDeviceProfile.inv.numRows) {
2079 customValuesChanged = true;
2083 if (gridSize != size.getValue() || customValuesChanged) {
2084 SettingsProvider.putInt(this,
2085 SettingsProvider.SETTINGS_UI_DYNAMIC_GRID_SIZE, size.getValue());
2086 reloadLauncher(true, true);
2089 // Must be called after reload and before settings invalidation.
2090 sRemoteFolderManager.onGridSizeChanged();
2092 mOverviewSettingsPanel.notifyDataSetInvalidated();
2094 FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
2095 Configuration config = getResources().getConfiguration();
2096 if(config.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
2098 .setCustomAnimations(0, R.anim.exit_out_left);
2101 .setCustomAnimations(0, R.anim.exit_out_right);
2104 .remove(mDynamicGridSizeFragment).commit();
2105 unlockScreenOrientation(true);
2106 mDarkPanel.setVisibility(View.VISIBLE);
2107 ObjectAnimator anim = ObjectAnimator.ofFloat(
2108 mDarkPanel, "alpha", 0.3f, 0.0f);
2110 anim.addListener(mAnimatorListener);
2114 public void onAttachedToWindow() {
2115 super.onAttachedToWindow();
2117 // Listen for broadcasts related to user-presence
2118 final IntentFilter filter = new IntentFilter();
2119 filter.addAction(Intent.ACTION_SCREEN_OFF);
2120 filter.addAction(Intent.ACTION_USER_PRESENT);
2121 // For handling managed profiles
2122 if (ENABLE_DEBUG_INTENTS) {
2123 filter.addAction(DebugIntents.DELETE_DATABASE);
2124 filter.addAction(DebugIntents.MIGRATE_DATABASE);
2126 registerReceiver(mReceiver, filter);
2127 FirstFrameAnimatorHelper.initializeDrawListener(getWindow().getDecorView());
2128 setupTransparentSystemBarsForLollipop();
2134 * Sets up transparent navigation and status bars in Lollipop.
2135 * This method is a no-op for other platform versions.
2137 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
2138 private void setupTransparentSystemBarsForLollipop() {
2139 if (Utilities.ATLEAST_LOLLIPOP) {
2140 Window window = getWindow();
2141 window.getAttributes().systemUiVisibility |=
2142 (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
2143 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
2144 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
2145 window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
2146 | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2147 window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
2148 window.setStatusBarColor(Color.TRANSPARENT);
2149 window.setNavigationBarColor(Color.TRANSPARENT);
2154 public void onDetachedFromWindow() {
2155 super.onDetachedFromWindow();
2159 unregisterReceiver(mReceiver);
2162 updateAutoAdvanceState();
2165 public void onWindowVisibilityChanged(int visibility) {
2166 mVisible = visibility == View.VISIBLE;
2167 updateAutoAdvanceState();
2168 // The following code used to be in onResume, but it turns out onResume is called when
2169 // you're in All Apps and click home to go to the workspace. onWindowVisibilityChanged
2170 // is a more appropriate event to handle
2172 if (!mWorkspaceLoading) {
2173 final ViewTreeObserver observer = mWorkspace.getViewTreeObserver();
2174 // We want to let Launcher draw itself at least once before we force it to build
2175 // layers on all the workspace pages, so that transitioning to Launcher from other
2176 // apps is nice and speedy.
2177 observer.addOnDrawListener(new ViewTreeObserver.OnDrawListener() {
2178 private boolean mStarted = false;
2179 public void onDraw() {
2180 if (mStarted) return;
2182 // We delay the layer building a bit in order to give
2183 // other message processing a time to run. In particular
2184 // this avoids a delay in hiding the IME if it was
2185 // currently shown, because doing that may involve
2186 // some communication back with the app.
2187 mWorkspace.postDelayed(mBuildLayersRunnable, 500);
2188 final ViewTreeObserver.OnDrawListener listener = this;
2189 mWorkspace.post(new Runnable() {
2191 if (mWorkspace != null &&
2192 mWorkspace.getViewTreeObserver() != null) {
2193 mWorkspace.getViewTreeObserver().
2194 removeOnDrawListener(listener);
2206 @Thunk void sendAdvanceMessage(long delay) {
2207 mHandler.removeMessages(ADVANCE_MSG);
2208 Message msg = mHandler.obtainMessage(ADVANCE_MSG);
2209 mHandler.sendMessageDelayed(msg, delay);
2210 mAutoAdvanceSentTime = System.currentTimeMillis();
2213 @Thunk void updateAutoAdvanceState() {
2214 boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
2215 if (autoAdvanceRunning != mAutoAdvanceRunning) {
2216 mAutoAdvanceRunning = autoAdvanceRunning;
2217 if (autoAdvanceRunning) {
2218 long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
2219 sendAdvanceMessage(delay);
2221 if (!mWidgetsToAdvance.isEmpty()) {
2222 mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
2223 (System.currentTimeMillis() - mAutoAdvanceSentTime));
2225 mHandler.removeMessages(ADVANCE_MSG);
2226 mHandler.removeMessages(0); // Remove messages sent using postDelayed()
2231 @Thunk final Handler mHandler = new Handler(new Handler.Callback() {
2234 public boolean handleMessage(Message msg) {
2235 if (msg.what == ADVANCE_MSG) {
2237 for (View key: mWidgetsToAdvance.keySet()) {
2238 final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
2239 final int delay = mAdvanceStagger * i;
2240 if (v instanceof Advanceable) {
2241 mHandler.postDelayed(new Runnable() {
2243 ((Advanceable) v).advance();
2249 sendAdvanceMessage(mAdvanceInterval);
2255 void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
2256 if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
2257 View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
2258 if (v instanceof Advanceable) {
2259 mWidgetsToAdvance.put(hostView, appWidgetInfo);
2260 ((Advanceable) v).fyiWillBeAdvancedByHostKThx();
2261 updateAutoAdvanceState();
2265 void removeWidgetToAutoAdvance(View hostView) {
2266 if (mWidgetsToAdvance.containsKey(hostView)) {
2267 mWidgetsToAdvance.remove(hostView);
2268 updateAutoAdvanceState();
2272 public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
2273 removeWidgetToAutoAdvance(launcherInfo.hostView);
2274 launcherInfo.hostView = null;
2275 AppWidgetProviderInfo info = mAppWidgetManager.getAppWidgetInfo(launcherInfo.appWidgetId);
2277 String packageName = info.providerInfo.packageName;
2281 public void showOutOfSpaceMessage(boolean isHotseatLayout) {
2282 int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space);
2283 Toast.makeText(this, getString(strId), Toast.LENGTH_SHORT).show();
2286 public DragLayer getDragLayer() {
2290 public AllAppsContainerView getAppsView() {
2294 public WidgetsContainerView getWidgetsView() {
2295 return mWidgetsView;
2298 public Workspace getWorkspace() {
2302 public RemoteFolderManager getRemoteFolderManager() {
2303 return sRemoteFolderManager;
2306 public Hotseat getHotseat() {
2310 public View getPageIndicator() {
2311 return mPageIndicators;
2314 public ViewGroup getOverviewPanel() {
2315 return mOverviewPanel;
2318 public View getDarkPanel() {
2322 public SearchDropTargetBar getSearchDropTargetBar() {
2323 return mSearchDropTargetBar;
2326 public LauncherAppWidgetHost getAppWidgetHost() {
2327 return mAppWidgetHost;
2330 public LauncherModel getModel() {
2334 protected SharedPreferences getSharedPrefs() {
2335 return mSharedPrefs;
2338 public DeviceProfile getDeviceProfile() {
2339 return mDeviceProfile;
2342 public void closeSystemDialogs() {
2343 getWindow().closeAllPanels();
2345 // Whatever we were doing is hereby canceled.
2346 setWaitingForResult(false);
2350 protected void onNewIntent(Intent intent) {
2352 if (DEBUG_RESUME_TIME) {
2353 startTime = System.currentTimeMillis();
2355 super.onNewIntent(intent);
2358 Folder openFolder = mWorkspace.getOpenFolder();
2359 boolean alreadyOnHome = mHasFocus && ((intent.getFlags() &
2360 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
2361 != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2362 boolean isActionMain = Intent.ACTION_MAIN.equals(intent.getAction());
2364 // also will cancel mWaitingForResult.
2365 closeSystemDialogs();
2367 if (mWorkspace == null) {
2368 // Can be cases where mWorkspace is null, this prevents a NPE
2371 // In all these cases, only animate if we're already on home
2372 mWorkspace.exitWidgetResizeMode();
2375 exitSpringLoadedDragMode();
2377 // If we are already on home, then just animate back to the workspace,
2378 // otherwise, just wait until onResume to set the state back to Workspace
2379 if (alreadyOnHome) {
2380 showWorkspace(true);
2382 mOnResumeState = State.WORKSPACE;
2385 final View v = getWindow().peekDecorView();
2386 if (v != null && v.getWindowToken() != null) {
2387 InputMethodManager imm = (InputMethodManager) getSystemService(
2388 INPUT_METHOD_SERVICE);
2389 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
2392 // Reset the apps view
2393 if (!alreadyOnHome && mAppsView != null) {
2394 mAppsView.scrollToTop();
2397 // Reset the widgets view
2398 if (!alreadyOnHome && mWidgetsView != null) {
2399 mWidgetsView.scrollToTop();
2402 if (mLauncherCallbacks != null) {
2403 mLauncherCallbacks.onHomeIntent();
2407 if (mLauncherCallbacks != null) {
2408 mLauncherCallbacks.onNewIntent(intent);
2411 // Defer moving to the default screen until after we callback to the LauncherCallbacks
2412 // as slow logic in the callbacks eat into the time the scroller expects for the snapToPage
2415 boolean moveToDefaultScreen = mLauncherCallbacks != null ?
2416 mLauncherCallbacks.shouldMoveToDefaultScreenOnHomeIntent() : true;
2417 if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive() &&
2418 openFolder == null && moveToDefaultScreen) {
2419 mWorkspace.post(new Runnable() {
2422 if (mWorkspace != null) {
2423 mWorkspace.moveToDefaultScreen(true);
2430 if (DEBUG_RESUME_TIME) {
2431 Log.d(TAG, "Time spent in onNewIntent: " + (System.currentTimeMillis() - startTime));
2436 public void onRestoreInstanceState(Bundle state) {
2437 super.onRestoreInstanceState(state);
2438 for (int page: mSynchronouslyBoundPages) {
2439 mWorkspace.restoreInstanceStateForChild(page);
2444 protected void onSaveInstanceState(Bundle outState) {
2445 if (mWorkspace.getChildCount() > 0) {
2446 outState.putInt(RUNTIME_STATE_CURRENT_SCREEN,
2447 mWorkspace.getCurrentPageOffsetFromCustomContent());
2449 super.onSaveInstanceState(outState);
2451 outState.putInt(RUNTIME_STATE, mState.ordinal());
2452 // We close any open folder since it will not be re-opened, and we need to make sure
2453 // this state is reflected.
2454 if (mHiddenFolderIcon == null) {
2458 if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screenId > -1 &&
2459 mWaitingForResult) {
2460 outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
2461 outState.putLong(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screenId);
2462 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
2463 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
2464 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, mPendingAddInfo.spanX);
2465 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, mPendingAddInfo.spanY);
2466 outState.putParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO, mPendingAddWidgetInfo);
2467 outState.putInt(RUNTIME_STATE_PENDING_ADD_WIDGET_ID, mPendingAddWidgetId);
2470 // Save the current widgets tray?
2472 outState.putSerializable(RUNTIME_STATE_VIEW_IDS, mItemIdToViewId);
2474 if (mLauncherCallbacks != null) {
2475 mLauncherCallbacks.onSaveInstanceState(outState);
2480 public void onDestroy() {
2483 // Remove all pending runnables
2484 mHandler.removeMessages(ADVANCE_MSG);
2485 mHandler.removeMessages(0);
2486 mWorkspace.removeCallbacks(mBuildLayersRunnable);
2488 // Stop callbacks from LauncherModel
2489 LauncherAppState app = (LauncherAppState.getInstance());
2491 // It's possible to receive onDestroy after a new Launcher activity has
2492 // been created. In this case, don't interfere with the new Launcher.
2493 if (mModel.isCurrentCallbacks(this)) {
2494 mModel.stopLoader();
2495 app.setLauncher(null);
2499 mAppWidgetHost.stopListening();
2500 } catch (NullPointerException ex) {
2501 Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
2503 mAppWidgetHost = null;
2505 mWidgetsToAdvance.clear();
2507 TextKeyListener.getInstance().release();
2509 unregisterReceiver(mCloseSystemDialogsReceiver);
2510 unregisterReceiver(mConnectionReceiver);
2511 unregisterReceiver(mDeviceUnlockedReceiver);
2513 mDragLayer.clearAllResizeFrames();
2514 ((ViewGroup) mWorkspace.getParent()).removeAllViews();
2515 mWorkspace.removeAllWorkspaceScreens();
2517 mDragController = null;
2519 LauncherAnimUtils.onDestroyActivity();
2521 if (mLauncherCallbacks != null) {
2522 mLauncherCallbacks.onDestroy();
2525 unregisterReceiver(protectedAppsChangedReceiver);
2526 unregisterReceiver(searchBarVisibilityChangedReceiver);
2529 public boolean getIsHiddenMenuOptionEnabled(){
2530 return mIsHiddenMenuOptionEnabled;
2533 public DragController getDragController() {
2534 return mDragController;
2537 public void validateLockForHiddenFolders(FolderIcon info, int action) {
2538 mHiddenFolderIcon = info;
2539 // Validate Lock Pattern
2540 Intent lockPatternActivity = new Intent();
2541 lockPatternActivity.setClassName(
2542 "com.android.settings",
2543 "com.android.settings.applications.LockPatternActivity");
2544 startActivityForResult(lockPatternActivity, action);
2545 mHiddenFolderAuth = false;
2548 public void notifyFolderNameChanged() {
2550 mModel.resetLoadedState(true, true);
2551 mModel.startLoader(mWorkspace.getCurrentPage(), LauncherModel.LOADER_FLAG_NONE);
2555 public void startActivityForResult(Intent intent, int requestCode) {
2556 onStartForResult(requestCode);
2557 super.startActivityForResult(intent, requestCode);
2561 public void startIntentSenderForResult (IntentSender intent, int requestCode,
2562 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) {
2563 onStartForResult(requestCode);
2565 super.startIntentSenderForResult(intent, requestCode,
2566 fillInIntent, flagsMask, flagsValues, extraFlags, options);
2567 } catch (IntentSender.SendIntentException e) {
2568 throw new ActivityNotFoundException();
2572 private void onStartForResult(int requestCode) {
2573 if (requestCode >= 0) {
2574 setWaitingForResult(true);
2579 * Indicates that we want global search for this activity by setting the globalSearch
2580 * argument for {@link #startSearch} to true.
2583 public void startSearch(String initialQuery, boolean selectInitialQuery,
2584 Bundle appSearchData, boolean globalSearch) {
2586 if (initialQuery == null) {
2587 // Use any text typed in the launcher as the initial query
2588 initialQuery = getTypedText();
2590 if (appSearchData == null) {
2591 appSearchData = new Bundle();
2592 appSearchData.putString("source", "launcher-search");
2594 Rect sourceBounds = new Rect();
2595 if (mSearchDropTargetBar != null) {
2596 sourceBounds = mSearchDropTargetBar.getSearchBarBounds();
2599 boolean clearTextImmediately = startSearch(initialQuery, selectInitialQuery,
2600 appSearchData, sourceBounds);
2601 if (clearTextImmediately) {
2605 // We need to show the workspace after starting the search
2606 showWorkspace(true);
2610 * Start a text search.
2612 * @return {@code true} if the search will start immediately, so any further keypresses
2613 * will be handled directly by the search UI. {@code false} if {@link Launcher} should continue
2614 * to buffer keypresses.
2616 public boolean startSearch(String initialQuery,
2617 boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
2618 if (mLauncherCallbacks != null && mLauncherCallbacks.providesSearch()) {
2619 return mLauncherCallbacks.startSearch(initialQuery, selectInitialQuery, appSearchData,
2623 startGlobalSearch(initialQuery, selectInitialQuery,
2624 appSearchData, sourceBounds);
2629 * Starts the global search activity. This code is a copied from SearchManager
2631 private void startGlobalSearch(String initialQuery,
2632 boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
2633 final SearchManager searchManager =
2634 (SearchManager) getSystemService(Context.SEARCH_SERVICE);
2635 ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
2636 if (globalSearchActivity == null) {
2637 Log.w(TAG, "No global search activity found.");
2640 Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
2641 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2642 intent.setComponent(globalSearchActivity);
2643 // Make sure that we have a Bundle to put source in
2644 if (appSearchData == null) {
2645 appSearchData = new Bundle();
2647 appSearchData = new Bundle(appSearchData);
2649 // Set source to package name of app that starts global search if not set already.
2650 if (!appSearchData.containsKey("source")) {
2651 appSearchData.putString("source", getPackageName());
2653 intent.putExtra(SearchManager.APP_DATA, appSearchData);
2654 if (!TextUtils.isEmpty(initialQuery)) {
2655 intent.putExtra(SearchManager.QUERY, initialQuery);
2657 if (selectInitialQuery) {
2658 intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery);
2660 intent.setSourceBounds(sourceBounds);
2662 startActivity(intent);
2663 } catch (ActivityNotFoundException ex) {
2664 Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
2668 public void startSearchFromAllApps(View v, Intent searchIntent, String searchQuery) {
2669 if (mLauncherCallbacks != null && mLauncherCallbacks.startSearchFromAllApps(searchQuery)) {
2673 // If not handled, then just start the provided search intent
2674 startActivitySafely(v, searchIntent, null);
2677 public boolean isOnCustomContent() {
2678 return mWorkspace.isOnOrMovingToCustomContent();
2682 public boolean onPrepareOptionsMenu(Menu menu) {
2683 super.onPrepareOptionsMenu(menu);
2684 if (!isOnCustomContent()) {
2685 // Close any open folders
2687 // Stop resizing any widgets
2688 mWorkspace.exitWidgetResizeMode();
2689 if (!mWorkspace.isInOverviewMode()) {
2690 // Show the overview mode
2691 showOverviewMode(true);
2693 showWorkspace(true);
2696 if (mLauncherCallbacks != null) {
2697 return mLauncherCallbacks.onPrepareOptionsMenu(menu);
2704 public boolean onSearchRequested() {
2705 startSearch(null, false, null, true);
2706 // Use a custom animation for launching search
2710 public boolean isWorkspaceLocked() {
2711 return mWorkspaceLoading || mWaitingForResult;
2714 public boolean isWorkspaceLoading() {
2715 return mWorkspaceLoading;
2718 private void setWorkspaceLoading(boolean value) {
2719 boolean isLocked = isWorkspaceLocked();
2720 mWorkspaceLoading = value;
2721 if (isLocked != isWorkspaceLocked()) {
2722 onWorkspaceLockedChanged();
2726 private void setWaitingForResult(boolean value) {
2727 boolean isLocked = isWorkspaceLocked();
2728 mWaitingForResult = value;
2729 if (isLocked != isWorkspaceLocked()) {
2730 onWorkspaceLockedChanged();
2734 protected void onWorkspaceLockedChanged() {
2735 if (mLauncherCallbacks != null) {
2736 mLauncherCallbacks.onWorkspaceLockedChanged();
2740 private void resetAddInfo() {
2741 mPendingAddInfo.container = ItemInfo.NO_ID;
2742 mPendingAddInfo.screenId = -1;
2743 mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1;
2744 mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1;
2745 mPendingAddInfo.minSpanX = mPendingAddInfo.minSpanY = 1;
2746 mPendingAddInfo.dropPos = null;
2749 void addAppWidgetImpl(final int appWidgetId, final ItemInfo info, final
2750 AppWidgetHostView boundWidget, final LauncherAppWidgetProviderInfo appWidgetInfo) {
2751 addAppWidgetImpl(appWidgetId, info, boundWidget, appWidgetInfo, 0);
2754 void addAppWidgetImpl(final int appWidgetId, final ItemInfo info,
2755 final AppWidgetHostView boundWidget, final LauncherAppWidgetProviderInfo appWidgetInfo,
2757 if (appWidgetInfo.configure != null) {
2758 mPendingAddWidgetInfo = appWidgetInfo;
2759 mPendingAddWidgetId = appWidgetId;
2761 // Launch over to configure widget, if needed
2762 mAppWidgetManager.startConfigActivity(appWidgetInfo, appWidgetId, this,
2763 mAppWidgetHost, REQUEST_CREATE_APPWIDGET);
2766 // Otherwise just add it
2767 Runnable onComplete = new Runnable() {
2770 // Exit spring loaded mode if necessary after adding the widget
2771 exitSpringLoadedDragModeDelayed(true, EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT,
2775 completeAddAppWidget(appWidgetId, info.container, info.screenId, boundWidget,
2777 mWorkspace.removeExtraEmptyScreenDelayed(true, onComplete, delay, false);
2778 String packageName = appWidgetInfo.providerInfo.packageName;
2782 protected void moveToCustomContentScreen(boolean animate) {
2783 // Close any folders that may be open.
2785 mWorkspace.moveToCustomContentScreen(animate);
2788 public void addPendingItem(PendingAddItemInfo info, long container, long screenId,
2789 int[] cell, int spanX, int spanY) {
2790 switch (info.itemType) {
2791 case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
2792 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2793 int span[] = new int[2];
2796 addAppWidgetFromDrop((PendingAddWidgetInfo) info,
2797 container, screenId, cell, span);
2799 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2800 processShortcutFromDrop(info.componentName, container, screenId, cell);
2803 throw new IllegalStateException("Unknown item type: " + info.itemType);
2808 * Process a shortcut drop.
2810 * @param componentName The name of the component
2811 * @param screenId The ID of the screen where it should be added
2812 * @param cell The cell it should be added to, optional
2814 private void processShortcutFromDrop(ComponentName componentName, long container, long screenId,
2817 mPendingAddInfo.container = container;
2818 mPendingAddInfo.screenId = screenId;
2819 mPendingAddInfo.dropPos = null;
2822 mPendingAddInfo.cellX = cell[0];
2823 mPendingAddInfo.cellY = cell[1];
2826 Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2827 createShortcutIntent.setComponent(componentName);
2828 Utilities.startActivityForResultSafely(this, createShortcutIntent, REQUEST_CREATE_SHORTCUT);
2832 * Process a widget drop.
2834 * @param info The PendingAppWidgetInfo of the widget being added.
2835 * @param screenId The ID of the screen where it should be added
2836 * @param cell The cell it should be added to, optional
2838 private void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, long screenId,
2839 int[] cell, int[] span) {
2841 mPendingAddInfo.container = info.container = container;
2842 mPendingAddInfo.screenId = info.screenId = screenId;
2843 mPendingAddInfo.dropPos = null;
2844 mPendingAddInfo.minSpanX = info.minSpanX;
2845 mPendingAddInfo.minSpanY = info.minSpanY;
2848 mPendingAddInfo.cellX = cell[0];
2849 mPendingAddInfo.cellY = cell[1];
2852 mPendingAddInfo.spanX = span[0];
2853 mPendingAddInfo.spanY = span[1];
2856 AppWidgetHostView hostView = info.boundWidget;
2858 if (hostView != null) {
2859 appWidgetId = hostView.getAppWidgetId();
2860 addAppWidgetImpl(appWidgetId, info, hostView, info.info);
2862 // Clear the boundWidget so that it doesn't get destroyed.
2863 info.boundWidget = null;
2865 // In this case, we either need to start an activity to get permission to bind
2866 // the widget, or we need to start an activity to configure the widget, or both.
2867 appWidgetId = getAppWidgetHost().allocateAppWidgetId();
2868 Bundle options = info.bindOptions;
2870 boolean success = mAppWidgetManager.bindAppWidgetIdIfAllowed(
2871 appWidgetId, info.info, options);
2873 addAppWidgetImpl(appWidgetId, info, null, info.info);
2875 mPendingAddWidgetInfo = info.info;
2876 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
2877 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
2878 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.componentName);
2879 mAppWidgetManager.getUser(mPendingAddWidgetInfo)
2880 .addToIntent(intent, AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE);
2881 // TODO: we need to make sure that this accounts for the options bundle.
2882 // intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, options);
2883 startActivityForResult(intent, REQUEST_BIND_APPWIDGET);
2888 FolderIcon addFolder(CellLayout layout, long container, final long screenId, int cellX,
2890 FolderInfo folderInfo = new FolderInfo();
2891 folderInfo.title = getText(R.string.folder_name);
2892 return addFolder(layout, container, screenId, cellX, cellY, folderInfo);
2895 FolderIcon addFolder(CellLayout layout, long container, final long screenId, int cellX,
2896 int cellY, FolderInfo folderInfo) {
2898 LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screenId,
2900 sFolders.put(folderInfo.id, folderInfo);
2903 FolderIcon newFolder =
2904 FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache);
2905 if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
2906 newFolder.setTextVisible(!mHideIconLabels);
2908 mWorkspace.addInScreen(newFolder, container, screenId, cellX, cellY, 1, 1,
2909 isWorkspaceLocked());
2910 // Force measure the new folder icon
2911 CellLayout parent = mWorkspace.getParentCellLayoutForView(newFolder);
2912 parent.getShortcutsAndWidgets().measureChild(newFolder);
2916 void removeFolder(FolderInfo folder) {
2917 sFolders.remove(folder.id);
2921 public boolean dispatchKeyEvent(KeyEvent event) {
2922 if (event.getAction() == KeyEvent.ACTION_DOWN) {
2923 switch (event.getKeyCode()) {
2924 case KeyEvent.KEYCODE_HOME:
2926 case KeyEvent.KEYCODE_VOLUME_DOWN:
2927 if (Utilities.isPropertyEnabled(DUMP_STATE_PROPERTY)) {
2933 } else if (event.getAction() == KeyEvent.ACTION_UP) {
2934 switch (event.getKeyCode()) {
2935 case KeyEvent.KEYCODE_HOME:
2940 return super.dispatchKeyEvent(event);
2944 public void onBackPressed() {
2945 if (mLauncherCallbacks != null && mLauncherCallbacks.handleBackPressed()) {
2949 if (mDragController.isDragging()) {
2950 mDragController.cancelDrag();
2954 if (isAppsViewVisible()) {
2955 showWorkspace(true);
2956 } else if (isWidgetsViewVisible()) {
2957 showOverviewMode(true);
2958 } else if (mWorkspace.isInOverviewMode()) {
2959 Fragment gridFragment = getFragmentManager().findFragmentByTag(
2960 DynamicGridSizeFragment.DYNAMIC_GRID_SIZE_FRAGMENT);
2961 if (gridFragment != null) {
2962 ((DynamicGridSizeFragment) gridFragment).setSize();
2963 unlockScreenOrientation(true);
2966 showWorkspace(true);
2967 // Background was set to gradient in onPause(), restore to black if in all apps.
2968 setWorkspaceBackground(mState == State.WORKSPACE ? WORKSPACE_BACKGROUND_GRADIENT
2969 : WORKSPACE_BACKGROUND_TRANSPARENT);
2971 } else if (mWorkspace.getOpenFolder() != null) {
2972 Folder openFolder = mWorkspace.getOpenFolder();
2973 if (openFolder.isEditingName()) {
2974 openFolder.dismissEditingName();
2979 mWorkspace.exitWidgetResizeMode();
2981 // Back button is a no-op here, but give at least some feedback for the button press
2982 mWorkspace.showOutlinesTemporarily();
2988 * Re-listen when widget host is reset.
2991 public void onAppWidgetHostReset() {
2992 if (mAppWidgetHost != null) {
2993 mAppWidgetHost.startListening();
2998 * Launches the intent referred by the clicked shortcut.
3000 * @param v The view representing the clicked shortcut.
3002 public void onClick(View v) {
3003 // Make sure that rogue clicks don't get through while allapps is launching, or after the
3004 // view has detached (it's possible for this to happen if the view is removed mid touch).
3005 if (v.getWindowToken() == null) {
3009 if (!mWorkspace.isFinishedSwitchingState()) {
3013 if (v instanceof Workspace) {
3014 if (mWorkspace.isInOverviewMode()) {
3015 showWorkspace(true);
3020 if (v instanceof CellLayout) {
3021 if (mWorkspace.isInOverviewMode()) {
3022 showWorkspace(mWorkspace.indexOfChild(v), true);
3026 Object tag = v.getTag();
3027 if (tag instanceof ShortcutInfo) {
3028 onClickAppShortcut(v);
3029 } else if (tag instanceof FolderInfo) {
3030 if (v instanceof FolderIcon) {
3031 onClickFolderIcon(v);
3033 } else if (v == mAllAppsButton) {
3034 onClickAllAppsButton(v);
3035 } else if (tag instanceof AppInfo) {
3036 AppInfo info = (AppInfo) tag;
3037 startAppShortcutOrInfoActivity(v);
3038 } else if (tag instanceof LauncherAppWidgetInfo) {
3039 if (v instanceof PendingAppWidgetHostView) {
3040 onClickPendingWidget((PendingAppWidgetHostView) v);
3045 @SuppressLint("ClickableViewAccessibility")
3046 public boolean onTouch(View v, MotionEvent event) {
3051 * Event handler for the app widget view which has not fully restored.
3053 public void onClickPendingWidget(final PendingAppWidgetHostView v) {
3054 if (mIsSafeModeEnabled) {
3055 Toast.makeText(this, R.string.safemode_widget_error, Toast.LENGTH_SHORT).show();
3059 final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) v.getTag();
3060 if (v.isReadyForClickSetup()) {
3061 int widgetId = info.appWidgetId;
3062 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(widgetId);
3063 if (appWidgetInfo != null) {
3064 mPendingAddWidgetInfo = LauncherAppWidgetProviderInfo.fromProviderInfo(
3065 this, appWidgetInfo);
3066 mPendingAddInfo.copyFrom(info);
3067 mPendingAddWidgetId = widgetId;
3069 AppWidgetManagerCompat.getInstance(this).startConfigActivity(appWidgetInfo,
3070 info.appWidgetId, this, mAppWidgetHost, REQUEST_RECONFIGURE_APPWIDGET);
3072 } else if (info.installProgress < 0) {
3073 // The install has not been queued
3074 final String packageName = info.providerName.getPackageName();
3075 showBrokenAppInstallDialog(packageName,
3076 new DialogInterface.OnClickListener() {
3077 public void onClick(DialogInterface dialog, int id) {
3078 startActivitySafely(v, LauncherModel.getMarketIntent(packageName), info);
3082 // Download has started.
3083 final String packageName = info.providerName.getPackageName();
3084 startActivitySafely(v, LauncherModel.getMarketIntent(packageName), info);
3089 * Event handler for the "grid" button that appears on the home screen, which
3090 * enters all apps mode.
3092 * @param v The view that was clicked.
3094 protected void onClickAllAppsButton(View v) {
3095 if (LOGD) Log.d(TAG, "onClickAllAppsButton");
3096 if (!isAppsViewVisible()) {
3097 showAppsView(true /* animated */, false /* resetListToTop */,
3098 true /* updatePredictedApps */, false /* focusSearchBar */);
3100 if (mLauncherCallbacks != null) {
3101 mLauncherCallbacks.onClickAllAppsButton(v);
3106 protected void onLongClickAllAppsButton(View v) {
3107 if (LOGD) Log.d(TAG, "onLongClickAllAppsButton");
3108 if (!isAppsViewVisible()) {
3109 showAppsView(true /* animated */, false /* resetListToTop */,
3110 true /* updatePredictedApps */, true /* focusSearchBar */);
3114 private void showBrokenAppInstallDialog(final String packageName,
3115 DialogInterface.OnClickListener onSearchClickListener) {
3116 new AlertDialog.Builder(this)
3117 .setTitle(R.string.abandoned_promises_title)
3118 .setMessage(R.string.abandoned_promise_explanation)
3119 .setPositiveButton(R.string.abandoned_search, onSearchClickListener)
3120 .setNeutralButton(R.string.abandoned_clean_this,
3121 new DialogInterface.OnClickListener() {
3122 public void onClick(DialogInterface dialog, int id) {
3123 final UserHandleCompat user = UserHandleCompat.myUserHandle();
3124 mWorkspace.removeAbandonedPromise(packageName, user);
3132 * Event handler for an app shortcut click.
3134 * @param v The view that was clicked. Must be a tagged with a {@link ShortcutInfo}.
3136 protected void onClickAppShortcut(final View v) {
3137 if (LOGD) Log.d(TAG, "onClickAppShortcut");
3138 Object tag = v.getTag();
3139 if (!(tag instanceof ShortcutInfo)) {
3140 throw new IllegalArgumentException("Input must be a Shortcut");
3144 final ShortcutInfo shortcut = (ShortcutInfo) tag;
3146 if (shortcut.isDisabled != 0) {
3147 int error = R.string.activity_not_available;
3148 if ((shortcut.isDisabled & ShortcutInfo.FLAG_DISABLED_SAFEMODE) != 0) {
3149 error = R.string.safemode_shortcut_error;
3151 Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
3155 // Check for abandoned promise
3156 if ((v instanceof BubbleTextView)
3157 && shortcut.isPromise()
3158 && !shortcut.hasStatusFlag(ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE)) {
3159 showBrokenAppInstallDialog(
3160 shortcut.getTargetComponent().getPackageName(),
3161 new DialogInterface.OnClickListener() {
3162 public void onClick(DialogInterface dialog, int id) {
3163 startAppShortcutOrInfoActivity(v);
3170 startAppShortcutOrInfoActivity(v);
3172 if (mLauncherCallbacks != null) {
3173 mLauncherCallbacks.onClickAppShortcut(v);
3177 @Thunk void startAppShortcutOrInfoActivity(View v) {
3178 Object tag = v.getTag();
3179 final ShortcutInfo shortcut;
3180 final Intent intent;
3181 if (tag instanceof ShortcutInfo) {
3182 shortcut = (ShortcutInfo) tag;
3183 if (shortcut.isDisabled == 1) {
3184 Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_SHORT).show();
3187 intent = shortcut.intent;
3188 int[] pos = new int[2];
3189 v.getLocationOnScreen(pos);
3190 intent.setSourceBounds(new Rect(pos[0], pos[1],
3191 pos[0] + v.getWidth(), pos[1] + v.getHeight()));
3193 } else if (tag instanceof AppInfo) {
3195 intent = ((AppInfo) tag).intent;
3197 throw new IllegalArgumentException("Input must be a Shortcut or AppInfo");
3200 boolean success = startActivitySafely(v, intent, tag);
3201 mStats.recordLaunch(v, intent, shortcut);
3203 if (success && v instanceof BubbleTextView) {
3204 mWaitingForResume = (BubbleTextView) v;
3205 mWaitingForResume.setStayPressed(true);
3210 * Event handler for a folder icon click.
3212 * @param v The view that was clicked. Must be an instance of {@link FolderIcon}.
3214 protected void onClickFolderIcon(View v) {
3215 if (LOGD) Log.d(TAG, "onClickFolder");
3216 if (!(v instanceof FolderIcon)){
3217 throw new IllegalArgumentException("Input must be a FolderIcon");
3220 // TODO(sunnygoyal): Re-evaluate this code.
3221 FolderIcon folderIcon = (FolderIcon) v;
3222 final FolderInfo info = folderIcon.getFolderInfo();
3223 Folder openFolder = mWorkspace.getFolderForTag(info);
3225 int[] folderTouchXY = new int[2];
3226 v.getLocationOnScreen(folderTouchXY);
3227 int[] folderTouchXYOffset = {folderTouchXY[0] + v.getWidth() / 2,
3228 folderTouchXY[1] + v.getHeight() / 2};
3230 // If the folder info reports that the associated folder is open, then verify that
3231 // it is actually opened. There have been a few instances where this gets out of sync.
3232 if (info.opened && openFolder == null) {
3233 Log.d(TAG, "Folder info marked as open, but associated folder is not open. Screen: "
3234 + info.screenId + " (" + info.cellX + ", " + info.cellY + ")");
3235 info.opened = false;
3238 if (!info.opened && !folderIcon.getFolder().isDestroyed()) {
3239 // Close any open folder
3241 // Open the requested folder
3242 openFolder(folderIcon, folderTouchXYOffset);
3244 // Find the open folder...
3246 if (openFolder != null) {
3247 folderScreen = mWorkspace.getPageForView(openFolder);
3249 closeFolder(openFolder);
3250 if (folderScreen != mWorkspace.getCurrentPage()) {
3251 // Close any folder open on the current screen
3253 // Pull the folder onto this screen
3254 openFolder(folderIcon, folderTouchXYOffset);
3259 if (mLauncherCallbacks != null) {
3260 mLauncherCallbacks.onClickFolderIcon(v);
3265 * Event handler for the (Add) Widgets button that appears after a long press
3266 * on the home screen.
3268 protected void onClickAddWidgetButton(View view) {
3269 if (LOGD) Log.d(TAG, "onClickAddWidgetButton");
3270 if (mIsSafeModeEnabled) {
3271 Toast.makeText(this, R.string.safemode_widget_error, Toast.LENGTH_SHORT).show();
3273 showWidgetsView(true /* animated */, true /* resetPageToZero */);
3274 if (mLauncherCallbacks != null) {
3275 mLauncherCallbacks.onClickAddWidgetButton(view);
3281 * Event handler for the wallpaper picker button that appears after a long press
3282 * on the home screen.
3284 protected void onClickWallpaperPicker(View v) {
3285 if (LOGD) Log.d(TAG, "onClickWallpaperPicker");
3286 startActivityForResult(new Intent(Intent.ACTION_SET_WALLPAPER),
3287 REQUEST_PICK_WALLPAPER);
3289 if (mLauncherCallbacks != null) {
3290 mLauncherCallbacks.onClickWallpaperPicker(v);
3295 * Event handler for a click on the settings button that appears after a long press
3296 * on the home screen.
3298 protected void onClickSettingsButton(View v) {
3299 if (LOGD) Log.d(TAG, "onClickSettingsButton");
3300 if (mLauncherCallbacks != null) {
3301 mLauncherCallbacks.onClickSettingsButton(v);
3303 if (mOverviewPanel.isExpanded()) {
3304 mOverviewPanel.collapsePane();
3306 mOverviewPanel.expandPane();
3311 protected void onClickDefaultScreenButton(View v) {
3312 if (LOGD) Log.d(TAG, "onClickDefaultScreenButton");
3314 if (!mWorkspace.isInOverviewMode()) return;
3316 mDefaultScreenId = mWorkspace.getScreenIdForPageIndex(mWorkspace.getPageNearestToCenterOfScreen());
3317 updateDefaultScreenButton();
3318 SettingsProvider.get(this).edit()
3319 .putLong(SettingsProvider.SETTINGS_UI_HOMESCREEN_DEFAULT_SCREEN_ID,
3324 protected void updateDefaultScreenButton() {
3325 if (mOverviewPanel != null) {
3326 View defaultPageButton = mOverviewPanel.findViewById(R.id.default_screen_button);
3327 defaultPageButton.setActivated(
3328 mWorkspace.getScreenIdForPageIndex(mWorkspace.getPageNearestToCenterOfScreen())
3329 == mDefaultScreenId);
3333 public View.OnTouchListener getHapticFeedbackTouchListener() {
3334 if (mHapticFeedbackTouchListener == null) {
3335 mHapticFeedbackTouchListener = new View.OnTouchListener() {
3336 @SuppressLint("ClickableViewAccessibility")
3338 public boolean onTouch(View v, MotionEvent event) {
3339 if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) {
3340 v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
3346 return mHapticFeedbackTouchListener;
3349 public void onDragStarted(View view) {
3350 if (isOnCustomContent()) {
3351 // Custom content screen doesn't participate in drag and drop. If on custom
3352 // content screen, move to default.
3353 moveWorkspaceToDefaultScreen();
3356 if (mLauncherCallbacks != null) {
3357 mLauncherCallbacks.onDragStarted(view);
3362 * Called when the user stops interacting with the launcher.
3363 * This implies that the user is now on the homescreen and is not doing housekeeping.
3365 protected void onInteractionEnd() {
3366 if (mLauncherCallbacks != null) {
3367 mLauncherCallbacks.onInteractionEnd();
3372 * Called when the user starts interacting with the launcher.
3373 * The possible interactions are:
3375 * - reorder an app shortcut, or a widget
3376 * - open the overview mode.
3377 * This is a good time to stop doing things that only make sense
3378 * when the user is on the homescreen and not doing housekeeping.
3380 protected void onInteractionBegin() {
3381 if (mLauncherCallbacks != null) {
3382 mLauncherCallbacks.onInteractionBegin();
3386 /** Updates the interaction state. */
3387 public void updateInteraction(Workspace.State fromState, Workspace.State toState) {
3388 // Only update the interacting state if we are transitioning to/from a view with an
3390 boolean fromStateWithOverlay = fromState != Workspace.State.NORMAL;
3391 boolean toStateWithOverlay = toState != Workspace.State.NORMAL;
3392 if (toStateWithOverlay) {
3393 onInteractionBegin();
3394 } else if (fromStateWithOverlay) {
3399 void startApplicationDetailsActivity(ComponentName componentName, UserHandleCompat user) {
3401 LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this);
3402 launcherApps.showAppDetailsForProfile(componentName, user);
3403 } catch (SecurityException e) {
3404 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
3405 Log.e(TAG, "Launcher does not have permission to launch settings");
3406 } catch (ActivityNotFoundException e) {
3407 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
3408 Log.e(TAG, "Unable to launch settings");
3412 // returns true if the activity was started
3413 boolean startApplicationUninstallActivity(ComponentName componentName, int flags,
3414 UserHandleCompat user) {
3415 if ((flags & AppInfo.DOWNLOADED_FLAG) == 0) {
3416 // System applications cannot be installed. For now, show a toast explaining that.
3417 // We may give them the option of disabling apps this way.
3418 int messageId = R.string.uninstall_system_app_text;
3419 Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
3422 String packageName = componentName.getPackageName();
3423 String className = componentName.getClassName();
3424 Intent intent = new Intent(
3425 Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
3426 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
3427 Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
3429 user.addToIntent(intent, Intent.EXTRA_USER);
3431 startActivity(intent);
3436 private boolean startActivity(View v, Intent intent, Object tag) {
3438 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3440 // Only launch using the new animation if the shortcut has not opted out (this is a
3441 // private contract between launcher and may be ignored in the future).
3442 boolean useLaunchAnimation = (v != null) &&
3443 !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
3444 LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this);
3445 UserManagerCompat userManager = UserManagerCompat.getInstance(this);
3447 UserHandleCompat user = null;
3448 if (intent.hasExtra(AppInfo.EXTRA_PROFILE)) {
3449 long serialNumber = intent.getLongExtra(AppInfo.EXTRA_PROFILE, -1);
3450 user = userManager.getUserForSerialNumber(serialNumber);
3453 Bundle optsBundle = null;
3454 if (useLaunchAnimation) {
3455 ActivityOptions opts = null;
3456 if (Utilities.ATLEAST_MARSHMALLOW) {
3457 int left = 0, top = 0;
3458 int width = v.getMeasuredWidth(), height = v.getMeasuredHeight();
3459 if (v instanceof TextView) {
3460 // Launch from center of icon, not entire view
3461 Drawable icon = Workspace.getTextViewIcon((TextView) v);
3463 Rect bounds = icon.getBounds();
3464 left = (width - bounds.width()) / 2;
3465 top = v.getPaddingTop();
3466 width = bounds.width();
3467 height = bounds.height();
3470 opts = ActivityOptions.makeClipRevealAnimation(v, left, top, width, height);
3471 } else if (!Utilities.ATLEAST_LOLLIPOP) {
3472 // Below L, we use a scale up animation
3473 opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
3474 v.getMeasuredWidth(), v.getMeasuredHeight());
3475 } else if (Utilities.ATLEAST_LOLLIPOP_MR1) {
3476 // On L devices, we use the device default slide-up transition.
3477 // On L MR1 devices, we a custom version of the slide-up transition which
3478 // doesn't have the delay present in the device default.
3479 opts = ActivityOptions.makeCustomAnimation(this,
3480 R.anim.task_open_enter, R.anim.no_anim);
3482 optsBundle = opts != null ? opts.toBundle() : null;
3485 if (user == null || user.equals(UserHandleCompat.myUserHandle())) {
3486 // Could be launching some bookkeeping activity
3487 startActivity(intent, optsBundle);
3489 // TODO Component can be null when shortcuts are supported for secondary user
3490 launcherApps.startActivityForProfile(intent.getComponent(), user,
3491 intent.getSourceBounds(), optsBundle);
3494 } catch (SecurityException | NullPointerException e) {
3495 if (Utilities.ATLEAST_MARSHMALLOW && tag instanceof ItemInfo) {
3496 // Due to legacy reasons, direct call shortcuts require Launchers to have the
3497 // corresponding permission. Show the appropriate permission prompt if that
3499 if (intent.getComponent() == null
3500 && Intent.ACTION_CALL.equals(intent.getAction())
3501 && checkSelfPermission(Manifest.permission.CALL_PHONE) !=
3502 PackageManager.PERMISSION_GRANTED) {
3503 // TODO: Rename sPendingAddItem to a generic name.
3504 sPendingAddItem = preparePendingAddArgs(REQUEST_PERMISSION_CALL_PHONE, intent,
3506 requestPermissions(new String[]{Manifest.permission.CALL_PHONE},
3507 REQUEST_PERMISSION_CALL_PHONE);
3511 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
3512 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
3513 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
3514 "or use the exported attribute for this activity. "
3515 + "tag="+ tag + " intent=" + intent, e);
3520 public boolean startActivitySafely(View v, Intent intent, Object tag) {
3521 boolean success = false;
3522 if (mIsSafeModeEnabled && !Utilities.isSystemApp(this, intent)) {
3523 Toast.makeText(this, R.string.safemode_shortcut_error, Toast.LENGTH_SHORT).show();
3527 success = startActivity(v, intent, tag);
3528 } catch (ActivityNotFoundException e) {
3529 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
3530 Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
3536 * This method draws the FolderIcon to an ImageView and then adds and positions that ImageView
3537 * in the DragLayer in the exact absolute location of the original FolderIcon.
3539 private void copyFolderIconToImage(FolderIcon fi) {
3540 final int width = fi.getMeasuredWidth();
3541 final int height = fi.getMeasuredHeight();
3543 // Lazy load ImageView, Bitmap and Canvas
3544 if (mFolderIconImageView == null) {
3545 mFolderIconImageView = new ImageView(this);
3547 if (mFolderIconBitmap == null || mFolderIconBitmap.getWidth() != width ||
3548 mFolderIconBitmap.getHeight() != height) {
3549 mFolderIconBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
3550 mFolderIconCanvas = new Canvas(mFolderIconBitmap);
3553 DragLayer.LayoutParams lp;
3554 if (mFolderIconImageView.getLayoutParams() instanceof DragLayer.LayoutParams) {
3555 lp = (DragLayer.LayoutParams) mFolderIconImageView.getLayoutParams();
3557 lp = new DragLayer.LayoutParams(width, height);
3560 // The layout from which the folder is being opened may be scaled, adjust the starting
3561 // view size by this scale factor.
3562 float scale = mDragLayer.getDescendantRectRelativeToSelf(fi, mRectForFolderAnimation);
3563 lp.customPosition = true;
3564 lp.x = mRectForFolderAnimation.left;
3565 lp.y = mRectForFolderAnimation.top;
3566 lp.width = (int) (scale * width);
3567 lp.height = (int) (scale * height);
3569 mFolderIconCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
3570 fi.draw(mFolderIconCanvas);
3571 mFolderIconImageView.setImageBitmap(mFolderIconBitmap);
3572 if (fi.getFolder() != null) {
3573 mFolderIconImageView.setPivotX(fi.getFolder().getPivotXForIconAnimation());
3574 mFolderIconImageView.setPivotY(fi.getFolder().getPivotYForIconAnimation());
3576 // Just in case this image view is still in the drag layer from a previous animation,
3577 // we remove it and re-add it.
3578 if (mDragLayer.indexOfChild(mFolderIconImageView) != -1) {
3579 mDragLayer.removeView(mFolderIconImageView);
3581 mDragLayer.addView(mFolderIconImageView, lp);
3582 if (fi.getFolder() != null) {
3583 fi.getFolder().bringToFront();
3587 private void growAndFadeOutFolderIcon(FolderIcon fi) {
3588 if (fi == null) return;
3589 PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
3590 PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
3591 PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
3593 FolderInfo info = (FolderInfo) fi.getTag();
3594 if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
3595 CellLayout cl = (CellLayout) fi.getParent().getParent();
3596 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams();
3597 cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY);
3600 // Push an ImageView copy of the FolderIcon into the DragLayer and hide the original
3601 copyFolderIconToImage(fi);
3602 fi.setVisibility(View.INVISIBLE);
3604 ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
3606 if (Utilities.ATLEAST_LOLLIPOP) {
3607 oa.setInterpolator(new LogDecelerateInterpolator(100, 0));
3609 oa.setDuration(getResources().getInteger(R.integer.config_folderExpandDuration));
3613 private void shrinkAndFadeInFolderIcon(final FolderIcon fi) {
3614 if (fi == null) return;
3615 PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
3616 PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
3617 PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
3619 final CellLayout cl = (CellLayout) fi.getParent().getParent();
3621 // We remove and re-draw the FolderIcon in-case it has changed
3622 mDragLayer.removeView(mFolderIconImageView);
3623 copyFolderIconToImage(fi);
3624 ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
3626 oa.setDuration(getResources().getInteger(R.integer.config_folderExpandDuration));
3627 oa.addListener(new AnimatorListenerAdapter() {
3629 public void onAnimationEnd(Animator animation) {
3631 cl.clearFolderLeaveBehind();
3632 // Remove the ImageView copy of the FolderIcon and make the original visible.
3633 mDragLayer.removeView(mFolderIconImageView);
3634 fi.setVisibility(View.VISIBLE);
3642 * Opens the user folder described by the specified tag. The opening of the folder
3643 * is animated relative to the specified View. If the View is null, no animation
3646 * @param folderIcon The FolderIcon describing the folder to open.
3648 public void openFolder(FolderIcon folderIcon, int[] folderTouch) {
3649 Folder folder = folderIcon.getFolder();
3651 if (folder.getState() == Folder.STATE_ANIMATING) {
3655 Folder openFolder = mWorkspace != null ? mWorkspace.getOpenFolder() : null;
3656 if (openFolder != null && openFolder != folder) {
3657 // Close any open folder before opening a folder.
3661 FolderInfo info = folder.mInfo;
3663 if (info.hidden && !mHiddenFolderAuth) {
3664 folder.startHiddenFolderManager(REQUEST_OPEN_PROTECTED_FOLDER);
3670 // While the folder is open, the position of the icon cannot change.
3671 ((CellLayout.LayoutParams) folderIcon.getLayoutParams()).canReorder = false;
3673 // Just verify that the folder hasn't already been added to the DragLayer.
3674 // There was a one-off crash where the folder had a parent already.
3675 if (folder.getParent() == null) {
3676 mDragLayer.addView(folder);
3677 mDragController.addDropTarget((DropTarget) folder);
3679 Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" +
3680 folder.getParent() + ").");
3683 folder.animateOpen();
3684 /*growAndFadeOutFolderIcon(folderIcon);*/
3686 // Notify the accessibility manager that this folder "window" has appeared and occluded
3687 // the workspace items
3688 folder.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3689 getDragLayer().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
3692 public void closeFolder() {
3696 public void closeFolder(boolean animate) {
3697 Folder folder = mWorkspace != null ? mWorkspace.getOpenFolder() : null;
3698 if (folder != null) {
3699 if (folder.isEditingName()) {
3700 folder.dismissEditingName();
3702 closeFolder(folder, animate);
3706 public void closeFolder(Folder folder) {
3707 closeFolder(folder, true);
3710 public void closeFolder(Folder folder, boolean animate) {
3711 final FolderInfo info = folder.getInfo();
3712 info.opened = false;
3714 mHiddenFolderAuth = false;
3717 ViewGroup parent = (ViewGroup) folder.getParent().getParent();
3718 if (parent != null) {
3719 FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo);
3720 /*shrinkAndFadeInFolderIcon(fi);*/
3722 ((CellLayout.LayoutParams) fi.getLayoutParams()).canReorder = true;
3725 folder.animateClosed(mHiddenFolderLockStateChanged ? false : animate);
3727 // Notify the accessibility manager that this folder "window" has disappeard and no
3728 // longer occludeds the workspace items
3729 getDragLayer().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3730 mHiddenFolderIcon = null;
3731 mHiddenFolderLockStateChanged = false;
3734 public boolean onLongClick(View v) {
3735 if (!isDraggingEnabled()) return false;
3736 if (isWorkspaceLocked()) return false;
3737 if (mState != State.WORKSPACE) return false;
3739 if (v == mAllAppsButton) {
3740 onLongClickAllAppsButton(v);
3744 if (v instanceof Workspace) {
3745 if (!mWorkspace.isInOverviewMode()) {
3746 if (!mWorkspace.isTouchActive()) {
3747 showOverviewMode(true);
3748 mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
3749 HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
3759 CellLayout.CellInfo longClickCellInfo = null;
3760 View itemUnderLongClick = null;
3761 if (v.getTag() instanceof ItemInfo) {
3762 ItemInfo info = (ItemInfo) v.getTag();
3763 longClickCellInfo = new CellLayout.CellInfo(v, info);
3764 itemUnderLongClick = longClickCellInfo.cell;
3768 // The hotseat touch handling does not go through Workspace, and we always allow long press
3769 // on hotseat items.
3770 final boolean inHotseat = isHotseatLayout(v);
3771 if (!mDragController.isDragging()) {
3772 if (itemUnderLongClick == null) {
3773 // User long pressed on empty space
3774 mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
3775 HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
3776 if (mWorkspace.isInOverviewMode()) {
3777 mWorkspace.startReordering(v);
3779 showOverviewMode(true);
3782 final boolean isAllAppsButton = inHotseat && isAllAppsButtonRank(
3783 mHotseat.getOrderInHotseat(
3784 longClickCellInfo.cellX,
3785 longClickCellInfo.cellY));
3786 if (!(itemUnderLongClick instanceof Folder || isAllAppsButton)) {
3787 // User long pressed on an item
3788 mWorkspace.startDrag(longClickCellInfo);
3795 boolean isHotseatLayout(View layout) {
3796 return mHotseat != null && layout != null &&
3797 (layout instanceof CellLayout) && (layout == mHotseat.getLayout());
3801 * Returns the CellLayout of the specified container at the specified screen.
3803 public CellLayout getCellLayout(long container, long screenId) {
3804 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
3805 if (mHotseat != null) {
3806 return mHotseat.getLayout();
3811 return mWorkspace.getScreenWithId(screenId);
3816 * For overridden classes.
3818 public boolean isAllAppsVisible() {
3819 return isAppsViewVisible();
3822 public boolean isAppsViewVisible() {
3823 return (mState == State.APPS) || (mOnResumeState == State.APPS);
3826 public boolean isWidgetsViewVisible() {
3827 return (mState == State.WIDGETS) || (mOnResumeState == State.WIDGETS);
3830 private void setWorkspaceBackground(int background) {
3831 switch (background) {
3832 case WORKSPACE_BACKGROUND_TRANSPARENT:
3833 getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
3835 case WORKSPACE_BACKGROUND_BLACK:
3836 getWindow().setBackgroundDrawable(null);
3839 getWindow().setBackgroundDrawable(mWorkspaceBackgroundDrawable);
3843 protected void changeWallpaperVisiblity(boolean visible) {
3844 int wpflags = visible ? WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER : 0;
3845 int curflags = getWindow().getAttributes().flags
3846 & WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
3847 if (wpflags != curflags) {
3848 getWindow().setFlags(wpflags, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
3850 setWorkspaceBackground(visible ? WORKSPACE_BACKGROUND_GRADIENT : WORKSPACE_BACKGROUND_BLACK);
3854 public void onTrimMemory(int level) {
3855 super.onTrimMemory(level);
3856 if (level >= ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
3857 // The widget preview db can result in holding onto over
3858 // 3MB of memory for caching which isn't necessary.
3859 SQLiteDatabase.releaseMemory();
3861 // This clears all widget bitmaps from the widget tray
3864 if (mLauncherCallbacks != null) {
3865 mLauncherCallbacks.onTrimMemory(level);
3869 public void showWorkspace(boolean animated) {
3870 showWorkspace(WorkspaceStateTransitionAnimation.SCROLL_TO_CURRENT_PAGE, animated, null);
3873 public void showWorkspace(boolean animated, Runnable onCompleteRunnable) {
3874 showWorkspace(WorkspaceStateTransitionAnimation.SCROLL_TO_CURRENT_PAGE, animated,
3875 onCompleteRunnable);
3878 protected void showWorkspace(int snapToPage, boolean animated) {
3879 showWorkspace(snapToPage, animated, null);
3882 void showWorkspace(int snapToPage, boolean animated, Runnable onCompleteRunnable) {
3883 boolean changed = mState != State.WORKSPACE ||
3884 mWorkspace.getState() != Workspace.State.NORMAL;
3886 // Close overview mode if open
3887 if (mWorkspace.isInOverviewMode()) {
3888 mWorkspace.exitOverviewMode();
3890 mWorkspace.setVisibility(View.VISIBLE);
3891 mStateTransitionAnimation.startAnimationToWorkspace(mState, mWorkspace.getState(),
3892 Workspace.State.NORMAL, snapToPage, animated, onCompleteRunnable);
3894 // Set focus to the AppsCustomize button
3895 if (mAllAppsButton != null) {
3896 mAllAppsButton.requestFocus();
3900 // Change the state *after* we've called all the transition code
3901 mState = State.WORKSPACE;
3902 setWorkspaceBackground(mState == State.WORKSPACE ? WORKSPACE_BACKGROUND_GRADIENT
3903 : WORKSPACE_BACKGROUND_TRANSPARENT);
3905 // Resume the auto-advance of widgets
3906 mUserPresent = true;
3907 updateAutoAdvanceState();
3910 // Send an accessibility event to announce the context change
3911 getWindow().getDecorView()
3912 .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3916 void showOverviewMode(boolean animated) {
3917 mWorkspace.setVisibility(View.VISIBLE);
3918 mStateTransitionAnimation.startAnimationToWorkspace(mState, mWorkspace.getState(),
3919 Workspace.State.OVERVIEW,
3920 WorkspaceStateTransitionAnimation.SCROLL_TO_CURRENT_PAGE, animated,
3921 null /* onCompleteRunnable */);
3922 mState = State.WORKSPACE;
3926 * Shows the apps view.
3928 void showAppsView(boolean animated, boolean resetListToTop, boolean updatePredictedApps,
3929 boolean focusSearchBar) {
3930 if (resetListToTop) {
3931 mAppsView.scrollToTop();
3933 if (updatePredictedApps) {
3934 tryAndUpdatePredictedApps();
3936 showAppsOrWidgets(State.APPS, animated, focusSearchBar);
3938 sRemoteFolderManager.onAppDrawerOpened();
3942 * Shows the widgets view.
3944 void showWidgetsView(boolean animated, boolean resetPageToZero) {
3945 if (LOGD) Log.d(TAG, "showWidgetsView:" + animated + " resetPageToZero:" + resetPageToZero);
3946 if (resetPageToZero) {
3947 mWidgetsView.scrollToTop();
3949 showAppsOrWidgets(State.WIDGETS, animated, false);
3951 mWidgetsView.post(new Runnable() {
3954 mWidgetsView.requestFocus();
3960 * Sets up the transition to show the apps/widgets view.
3962 * @return whether the current from and to state allowed this operation
3964 // TODO: calling method should use the return value so that when {@code false} is returned
3965 // the workspace transition doesn't fall into invalid state.
3966 private boolean showAppsOrWidgets(State toState, boolean animated, boolean focusSearchBar) {
3967 if (mState != State.WORKSPACE && mState != State.APPS_SPRING_LOADED &&
3968 mState != State.WIDGETS_SPRING_LOADED) {
3971 if (toState != State.APPS && toState != State.WIDGETS) {
3975 if (toState == State.APPS) {
3976 mStateTransitionAnimation.startAnimationToAllApps(mWorkspace.getState(), animated,
3979 mStateTransitionAnimation.startAnimationToWidgets(mWorkspace.getState(), animated);
3982 // Change the state *after* we've called all the transition code
3985 // Pause the auto-advance of widgets until we are out of AllApps
3986 mUserPresent = false;
3987 updateAutoAdvanceState();
3990 // Send an accessibility event to announce the context change
3991 getWindow().getDecorView()
3992 .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3997 * Updates the workspace and interaction state on state change, and return the animation to this
4000 public Animator startWorkspaceStateChangeAnimation(Workspace.State toState, int toPage,
4001 boolean animated, HashMap<View, Integer> layerViews) {
4002 Workspace.State fromState = mWorkspace.getState();
4003 Animator anim = mWorkspace.setStateWithAnimation(toState, toPage, animated, layerViews);
4004 updateInteraction(fromState, toState);
4008 public void enterSpringLoadedDragMode() {
4009 if (LOGD) Log.d(TAG, String.format("enterSpringLoadedDragMode [mState=%s", mState.name()));
4010 if (mState == State.WORKSPACE || mState == State.APPS_SPRING_LOADED ||
4011 mState == State.WIDGETS_SPRING_LOADED) {
4015 mStateTransitionAnimation.startAnimationToWorkspace(mState, mWorkspace.getState(),
4016 Workspace.State.SPRING_LOADED,
4017 WorkspaceStateTransitionAnimation.SCROLL_TO_CURRENT_PAGE, true /* animated */,
4018 null /* onCompleteRunnable */);
4019 mState = isAppsViewVisible() ? State.APPS_SPRING_LOADED : State.WIDGETS_SPRING_LOADED;
4022 public void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, int delay,
4023 final Runnable onCompleteRunnable) {
4024 if (mState != State.APPS_SPRING_LOADED && mState != State.WIDGETS_SPRING_LOADED) return;
4026 mHandler.postDelayed(new Runnable() {
4029 if (successfulDrop) {
4030 // TODO(hyunyoungs): verify if this hack is still needed, if not, delete.
4032 // Before we show workspace, hide all apps again because
4033 // exitSpringLoadedDragMode made it visible. This is a bit hacky; we should
4034 // clean up our state transition functions
4035 mWidgetsView.setVisibility(View.GONE);
4036 showWorkspace(true, onCompleteRunnable);
4038 exitSpringLoadedDragMode();
4044 void exitSpringLoadedDragMode() {
4045 if (mState == State.APPS_SPRING_LOADED) {
4046 showAppsView(true /* animated */, false /* resetListToTop */,
4047 false /* updatePredictedApps */, false /* focusSearchBar */);
4048 } else if (mState == State.WIDGETS_SPRING_LOADED) {
4049 showWidgetsView(true, false);
4054 * Updates the set of predicted apps if it hasn't been updated since the last time Launcher was
4057 private void tryAndUpdatePredictedApps() {
4058 boolean mRemoteDrawerEnabled = SettingsProvider.getBoolean(this,
4059 SettingsProvider.SETTINGS_UI_DRAWER_REMOTE_APPS,
4060 R.bool.preferences_interface_drawer_remote_apps_default);
4061 if (!mRemoteDrawerEnabled) {
4062 if (mLauncherCallbacks != null) {
4063 List<ComponentKey> apps = mLauncherCallbacks.getPredictedApps();
4065 mAppsView.setPredictedAppComponents(apps);
4071 void lockAllApps() {
4075 void unlockAllApps() {
4079 protected void disableVoiceButtonProxy(boolean disable) {
4083 public View getOrCreateQsbBar() {
4084 if (mLauncherCallbacks != null && mLauncherCallbacks.providesSearch()) {
4085 return mLauncherCallbacks.getQsbBar();
4089 AppWidgetProviderInfo searchProvider = Utilities.getSearchWidgetProvider(this);
4090 if (searchProvider == null) {
4094 Bundle opts = new Bundle();
4095 opts.putInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY,
4096 AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX);
4098 SharedPreferences sp = getSharedPreferences(
4099 LauncherAppState.getSharedPreferencesKey(), MODE_PRIVATE);
4100 int widgetId = sp.getInt(QSB_WIDGET_ID, -1);
4101 AppWidgetProviderInfo widgetInfo = mAppWidgetManager.getAppWidgetInfo(widgetId);
4102 if (!searchProvider.provider.flattenToString().equals(
4103 sp.getString(QSB_WIDGET_PROVIDER, null))
4104 || (widgetInfo == null)
4105 || !widgetInfo.provider.equals(searchProvider.provider)) {
4106 // A valid widget is not already bound.
4107 if (widgetId > -1) {
4108 mAppWidgetHost.deleteAppWidgetId(widgetId);
4112 // Try to bind a new widget
4113 widgetId = mAppWidgetHost.allocateAppWidgetId();
4115 if (!AppWidgetManagerCompat.getInstance(this)
4116 .bindAppWidgetIdIfAllowed(widgetId, searchProvider, opts)) {
4117 mAppWidgetHost.deleteAppWidgetId(widgetId);
4122 .putInt(QSB_WIDGET_ID, widgetId)
4123 .putString(QSB_WIDGET_PROVIDER, searchProvider.provider.flattenToString())
4127 mAppWidgetHost.setQsbWidgetId(widgetId);
4128 if (widgetId != -1) {
4129 mQsb = mAppWidgetHost.createView(this, widgetId, searchProvider);
4130 mQsb.setId(R.id.qsb_widget);
4131 mQsb.updateAppWidgetOptions(opts);
4132 mQsb.setPadding(0, 0, 0, 0);
4133 mSearchDropTargetBar.addView(mQsb);
4134 mSearchDropTargetBar.setQsbSearchBar(mQsb);
4140 private void reinflateQSBIfNecessary() {
4141 if (mQsb instanceof LauncherAppWidgetHostView &&
4142 ((LauncherAppWidgetHostView) mQsb).isReinflateRequired()) {
4143 mSearchDropTargetBar.removeView(mQsb);
4145 mSearchDropTargetBar.setQsbSearchBar(getOrCreateQsbBar());
4150 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4151 final boolean result = super.dispatchPopulateAccessibilityEvent(event);
4152 final List<CharSequence> text = event.getText();
4154 // Populate event with a fake title based on the current state.
4155 if (mState == State.APPS) {
4156 text.add(getString(R.string.all_apps_button_label));
4157 } else if (mState == State.WIDGETS) {
4158 text.add(getString(R.string.widget_button_text));
4159 } else if (mWorkspace != null) {
4160 text.add(mWorkspace.getCurrentPageDescription());
4162 text.add(getString(R.string.all_apps_home_button_label));
4168 * Receives notifications when system dialogs are to be closed.
4170 @Thunk class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
4172 public void onReceive(Context context, Intent intent) {
4173 closeSystemDialogs();
4178 * If the activity is currently paused, signal that we need to run the passed Runnable
4181 * This needs to be called from incoming places where resources might have been loaded
4182 * while the activity is paused. That is because the Configuration (e.g., rotation) might be
4183 * wrong when we're not running, and if the activity comes back to what the configuration was
4184 * when we were paused, activity is not restarted.
4186 * Implementation of the method from LauncherModel.Callbacks.
4188 * @return {@code true} if we are currently paused. The caller might be able to skip some work
4190 @Thunk boolean waitUntilResume(Runnable run, boolean deletePreviousRunnables) {
4192 if (LOGD) Log.d(TAG, "Deferring update until onResume");
4193 if (deletePreviousRunnables) {
4194 while (mBindOnResumeCallbacks.remove(run)) {
4197 mBindOnResumeCallbacks.add(run);
4204 private boolean waitUntilResume(Runnable run) {
4205 return waitUntilResume(run, false);
4208 public void addOnResumeCallback(Runnable run) {
4209 mOnResumeCallbacks.add(run);
4213 * If the activity is currently paused, signal that we need to re-run the loader
4216 * This needs to be called from incoming places where resources might have been loaded
4217 * while we are paused. That is becaues the Configuration might be wrong
4218 * when we're not running, and if it comes back to what it was when we
4219 * were paused, we are not restarted.
4221 * Implementation of the method from LauncherModel.Callbacks.
4223 * @return true if we are currently paused. The caller might be able to
4224 * skip some work in that case since we will come back again.
4226 public boolean setLoadOnResume() {
4228 if (LOGD) Log.d(TAG, "setLoadOnResume");
4229 mOnResumeNeedsLoad = true;
4237 * Implementation of the method from LauncherModel.Callbacks.
4239 public int getCurrentWorkspaceScreen() {
4240 if (mWorkspace != null) {
4241 return mWorkspace.getCurrentPage();
4243 return SCREEN_COUNT / 2;
4248 * Refreshes the shortcuts shown on the workspace.
4250 * Implementation of the method from LauncherModel.Callbacks.
4252 public void startBinding() {
4253 setWorkspaceLoading(true);
4255 // If we're starting binding all over again, clear any bind calls we'd postponed in
4256 // the past (see waitUntilResume) -- we don't need them since we're starting binding
4257 // from scratch again
4258 mBindOnResumeCallbacks.clear();
4260 // Clear the workspace because it's going to be rebound
4261 mWorkspace.clearDropTargets();
4262 mWorkspace.removeAllWorkspaceScreens();
4264 mWidgetsToAdvance.clear();
4265 if (mHotseat != null) {
4266 mHotseat.resetLayout();
4271 public void bindScreens(ArrayList<Long> orderedScreenIds) {
4272 bindAddScreens(orderedScreenIds);
4274 // If there are no screens, we need to have an empty screen
4275 if (orderedScreenIds.size() == 0) {
4276 mWorkspace.addExtraEmptyScreen();
4279 // Create the custom content page (this call updates mDefaultScreen which calls
4280 // setCurrentPage() so ensure that all pages are added before calling this).
4281 if (hasCustomContentToLeft()) {
4282 mWorkspace.createCustomContentContainer();
4283 populateCustomContentContainer();
4286 LauncherModel.saveWidgetCount(this);
4287 LauncherModel.savePageCount(this);
4292 public void bindAddScreens(ArrayList<Long> orderedScreenIds) {
4293 int count = orderedScreenIds.size();
4294 for (int i = 0; i < count; i++) {
4295 mWorkspace.insertNewWorkspaceScreenBeforeEmptyScreen(orderedScreenIds.get(i));
4299 public void bindAppsAdded(final ArrayList<Long> newScreens,
4300 final ArrayList<ItemInfo> addNotAnimated,
4301 final ArrayList<ItemInfo> addAnimated,
4302 final ArrayList<AppInfo> addedApps) {
4303 Runnable r = new Runnable() {
4305 bindAppsAdded(newScreens, addNotAnimated, addAnimated, addedApps);
4308 if (waitUntilResume(r)) {
4312 // Add the new screens
4313 if (newScreens != null) {
4314 bindAddScreens(newScreens);
4317 // We add the items without animation on non-visible pages, and with
4318 // animations on the new page (which we will try and snap to).
4319 if (addNotAnimated != null && !addNotAnimated.isEmpty()) {
4320 bindItems(addNotAnimated, 0,
4321 addNotAnimated.size(), false);
4323 if (addAnimated != null && !addAnimated.isEmpty()) {
4324 bindItems(addAnimated, 0,
4325 addAnimated.size(), true);
4328 // Remove the extra empty screen
4329 mWorkspace.removeExtraEmptyScreen(false, false);
4331 if (addedApps != null && mAppsView != null) {
4332 mAppsView.addApps(addedApps);
4333 sRemoteFolderManager.onBindAddApps(addedApps);
4338 * Bind the items start-end from the list.
4340 * Implementation of the method from LauncherModel.Callbacks.
4342 public void bindItems(final ArrayList<ItemInfo> shortcuts, final int start, final int end,
4343 final boolean forceAnimateIcons) {
4344 Runnable r = new Runnable() {
4346 bindItems(shortcuts, start, end, forceAnimateIcons);
4349 if (waitUntilResume(r)) {
4353 // Get the list of added shortcuts and intersect them with the set of shortcuts here
4354 final AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
4355 final Collection<Animator> bounceAnims = new ArrayList<Animator>();
4356 final boolean animateIcons = forceAnimateIcons && canRunNewAppsAnimation();
4357 final Workspace workspace = mWorkspace;
4358 long newShortcutsScreenId = -1;
4359 for (int i = start; i < end; i++) {
4360 final ItemInfo item = shortcuts.get(i);
4362 // Short circuit if we are loading dock items for a configuration which has no dock
4363 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
4369 switch (item.itemType) {
4370 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
4371 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
4372 ShortcutInfo info = (ShortcutInfo) item;
4373 view = createShortcut(info);
4376 * TODO: FIX collision case
4378 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
4379 CellLayout cl = mWorkspace.getScreenWithId(item.screenId);
4380 if (cl != null && cl.isOccupied(item.cellX, item.cellY)) {
4381 View v = cl.getChildAt(item.cellX, item.cellY);
4382 Object tag = v.getTag();
4383 String desc = "Collision while binding workspace item: " + item
4384 + ". Collides with " + tag;
4385 if (LauncherAppState.isDogfoodBuild()) {
4386 throw (new RuntimeException(desc));
4393 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
4394 view = FolderIcon.fromXml(R.layout.folder_icon, this,
4395 (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
4396 (FolderInfo) item, mIconCache);
4400 ((FolderIcon) view).setTextVisible(!mHideIconLabels);
4403 throw new RuntimeException("Invalid Item Type");
4406 workspace.addInScreenFromBind(view, item.container, item.screenId, item.cellX,
4409 // Animate all the applications up now
4413 bounceAnims.add(createNewAppBounceAnimation(view, i));
4414 newShortcutsScreenId = item.screenId;
4419 // Animate to the correct page
4420 if (newShortcutsScreenId > -1) {
4421 long currentScreenId = mWorkspace.getScreenIdForPageIndex(mWorkspace.getNextPage());
4422 final int newScreenIndex = mWorkspace.getPageIndexForScreenId(newShortcutsScreenId);
4423 final Runnable startBounceAnimRunnable = new Runnable() {
4425 anim.playTogether(bounceAnims);
4429 if (newShortcutsScreenId != currentScreenId) {
4430 // We post the animation slightly delayed to prevent slowdowns
4431 // when we are loading right after we return to launcher.
4432 mWorkspace.postDelayed(new Runnable() {
4434 if (mWorkspace != null) {
4435 mWorkspace.snapToPage(newScreenIndex);
4436 mWorkspace.postDelayed(startBounceAnimRunnable,
4437 NEW_APPS_ANIMATION_DELAY);
4440 }, NEW_APPS_PAGE_MOVE_DELAY);
4442 mWorkspace.postDelayed(startBounceAnimRunnable, NEW_APPS_ANIMATION_DELAY);
4446 workspace.requestLayout();
4450 * Implementation of the method from LauncherModel.Callbacks.
4452 public void bindFolders(final LongArrayMap<FolderInfo> folders) {
4453 Runnable r = new Runnable() {
4455 bindFolders(folders);
4458 if (waitUntilResume(r)) {
4461 sFolders = folders.clone();
4465 * Add the views for a widget to the workspace.
4467 * Implementation of the method from LauncherModel.Callbacks.
4469 public void bindAppWidget(final LauncherAppWidgetInfo item) {
4470 Runnable r = new Runnable() {
4472 bindAppWidget(item);
4475 if (waitUntilResume(r)) {
4479 final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
4480 if (DEBUG_WIDGETS) {
4481 Log.d(TAG, "bindAppWidget: " + item);
4483 final Workspace workspace = mWorkspace;
4485 LauncherAppWidgetProviderInfo appWidgetInfo =
4486 LauncherModel.getProviderInfo(this, item.providerName, item.user);
4488 if (!mIsSafeModeEnabled
4489 && ((item.restoreStatus & LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0)
4490 && (item.restoreStatus != LauncherAppWidgetInfo.RESTORE_COMPLETED)) {
4492 if (appWidgetInfo == null) {
4493 if (DEBUG_WIDGETS) {
4494 Log.d(TAG, "Removing restored widget: id=" + item.appWidgetId
4495 + " belongs to component " + item.providerName
4496 + ", as the povider is null");
4498 LauncherModel.deleteItemFromDatabase(this, item);
4502 // If we do not have a valid id, try to bind an id.
4503 if ((item.restoreStatus & LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) != 0) {
4504 // Note: This assumes that the id remap broadcast is received before this step.
4505 // If that is not the case, the id remap will be ignored and user may see the
4506 // click to setup view.
4507 PendingAddWidgetInfo pendingInfo = new PendingAddWidgetInfo(this, appWidgetInfo, null);
4508 pendingInfo.spanX = item.spanX;
4509 pendingInfo.spanY = item.spanY;
4510 pendingInfo.minSpanX = item.minSpanX;
4511 pendingInfo.minSpanY = item.minSpanY;
4512 Bundle options = null;
4513 WidgetHostViewLoader.getDefaultOptionsForWidget(this, pendingInfo);
4515 int newWidgetId = mAppWidgetHost.allocateAppWidgetId();
4516 boolean success = mAppWidgetManager.bindAppWidgetIdIfAllowed(
4517 newWidgetId, appWidgetInfo, options);
4519 // TODO consider showing a permission dialog when the widget is clicked.
4521 mAppWidgetHost.deleteAppWidgetId(newWidgetId);
4522 if (DEBUG_WIDGETS) {
4523 Log.d(TAG, "Removing restored widget: id=" + item.appWidgetId
4524 + " belongs to component " + item.providerName
4525 + ", as the launcher is unable to bing a new widget id");
4527 LauncherModel.deleteItemFromDatabase(this, item);
4531 item.appWidgetId = newWidgetId;
4533 // If the widget has a configure activity, it is still needs to set it up, otherwise
4534 // the widget is ready to go.
4535 item.restoreStatus = (appWidgetInfo.configure == null)
4536 ? LauncherAppWidgetInfo.RESTORE_COMPLETED
4537 : LauncherAppWidgetInfo.FLAG_UI_NOT_READY;
4539 LauncherModel.updateItemInDatabase(this, item);
4540 } else if (((item.restoreStatus & LauncherAppWidgetInfo.FLAG_UI_NOT_READY) != 0)
4541 && (appWidgetInfo.configure == null)) {
4542 // If the ID is already valid, verify if we need to configure or not.
4543 item.restoreStatus = LauncherAppWidgetInfo.RESTORE_COMPLETED;
4544 LauncherModel.updateItemInDatabase(this, item);
4548 if (!mIsSafeModeEnabled && item.restoreStatus == LauncherAppWidgetInfo.RESTORE_COMPLETED) {
4549 final int appWidgetId = item.appWidgetId;
4550 if (DEBUG_WIDGETS) {
4551 Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component "
4552 + appWidgetInfo.provider);
4555 item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
4556 item.minSpanX = appWidgetInfo.minSpanX;
4557 item.minSpanY = appWidgetInfo.minSpanY;
4559 appWidgetInfo = null;
4560 PendingAppWidgetHostView view = new PendingAppWidgetHostView(this, item,
4561 mIsSafeModeEnabled);
4562 view.updateIcon(mIconCache);
4563 item.hostView = view;
4564 item.hostView.updateAppWidget(null);
4565 item.hostView.setOnClickListener(this);
4568 item.hostView.setTag(item);
4569 item.onBindAppWidget(this);
4571 workspace.addInScreen(item.hostView, item.container, item.screenId, item.cellX,
4572 item.cellY, item.spanX, item.spanY, false);
4573 if (!item.isCustomWidget()) {
4574 addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
4577 workspace.requestLayout();
4579 if (DEBUG_WIDGETS) {
4580 Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
4581 + (SystemClock.uptimeMillis()-start) + "ms");
4586 * Restores a pending widget.
4588 * @param appWidgetId The app widget id
4589 * @param cellInfo The position on screen where to create the widget.
4591 private void completeRestoreAppWidget(final int appWidgetId) {
4592 LauncherAppWidgetHostView view = mWorkspace.getWidgetForAppWidgetId(appWidgetId);
4593 if ((view == null) || !(view instanceof PendingAppWidgetHostView)) {
4594 Log.e(TAG, "Widget update called, when the widget no longer exists.");
4598 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) view.getTag();
4599 info.restoreStatus = LauncherAppWidgetInfo.RESTORE_COMPLETED;
4601 mWorkspace.reinflateWidgetsIfNecessary();
4602 LauncherModel.updateItemInDatabase(this, info);
4605 public void onPageBoundSynchronously(int page) {
4606 mSynchronouslyBoundPages.add(page);
4610 * Callback saying that there aren't any more items to bind.
4612 * Implementation of the method from LauncherModel.Callbacks.
4614 public void finishBindingItems() {
4615 Runnable r = new Runnable() {
4617 finishBindingItems();
4620 if (waitUntilResume(r)) {
4623 if (mSavedState != null) {
4624 if (!mWorkspace.hasFocus()) {
4625 mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
4630 mWorkspace.restoreInstanceStateForRemainingPages();
4632 setWorkspaceLoading(false);
4633 sendLoadingCompleteBroadcastIfNecessary();
4635 // If we received the result of any pending adds while the loader was running (e.g. the
4636 // widget configuration forced an orientation change), process them now.
4637 if (sPendingAddItem != null) {
4638 final long screenId = completeAdd(sPendingAddItem);
4640 // TODO: this moves the user to the page where the pending item was added. Ideally,
4641 // the screen would be guaranteed to exist after bind, and the page would be set through
4642 // the workspace restore process.
4643 mWorkspace.post(new Runnable() {
4646 mWorkspace.snapToScreenId(screenId);
4649 sPendingAddItem = null;
4652 InstallShortcutReceiver.disableAndFlushInstallQueue(this);
4654 if (mLauncherCallbacks != null) {
4655 mLauncherCallbacks.finishBindingItems(false);
4658 mWorkspace.stripEmptyScreens();
4660 sRemoteFolderManager.bindFinished();
4661 bindSearchProviderChanged();
4664 private void sendLoadingCompleteBroadcastIfNecessary() {
4665 if (!mSharedPrefs.getBoolean(FIRST_LOAD_COMPLETE, false)) {
4667 getResources().getString(R.string.receive_first_load_broadcast_permission);
4668 Intent intent = new Intent(ACTION_FIRST_LOAD_COMPLETE);
4669 sendBroadcast(intent, permission);
4670 SharedPreferences.Editor editor = mSharedPrefs.edit();
4671 editor.putBoolean(FIRST_LOAD_COMPLETE, true);
4676 public boolean isAllAppsButtonRank(int rank) {
4677 if (mHotseat != null) {
4678 return mHotseat.isAllAppsButtonRank(rank);
4683 private boolean canRunNewAppsAnimation() {
4684 long diff = System.currentTimeMillis() - mDragController.getLastGestureUpTime();
4685 return diff > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000)
4686 && (mClings == null || !mClings.isVisible());
4689 private ValueAnimator createNewAppBounceAnimation(View v, int i) {
4690 ValueAnimator bounceAnim = LauncherAnimUtils.ofPropertyValuesHolder(v,
4691 PropertyValuesHolder.ofFloat("alpha", 1f),
4692 PropertyValuesHolder.ofFloat("scaleX", 1f),
4693 PropertyValuesHolder.ofFloat("scaleY", 1f));
4694 bounceAnim.setDuration(InstallShortcutReceiver.NEW_SHORTCUT_BOUNCE_DURATION);
4695 bounceAnim.setStartDelay(i * InstallShortcutReceiver.NEW_SHORTCUT_STAGGER_DELAY);
4696 bounceAnim.setInterpolator(new OvershootInterpolator(BOUNCE_ANIMATION_TENSION));
4700 public boolean useVerticalBarLayout() {
4701 return mDeviceProfile.isVerticalBarLayout();
4704 protected Rect getSearchBarBounds() {
4705 return mDeviceProfile.getSearchBarBounds(Utilities.isRtl(getResources()));
4708 public void bindSearchProviderChanged() {
4709 if (mSearchDropTargetBar == null) {
4713 mSearchDropTargetBar.removeView(mQsb);
4716 mSearchDropTargetBar.setQsbSearchBar(getOrCreateQsbBar());
4720 * A runnable that we can dequeue and re-enqueue when all applications are bound (to prevent
4721 * multiple calls to bind the same list.)
4723 @Thunk ArrayList<AppInfo> mTmpAppsList;
4724 private Runnable mBindAllApplicationsRunnable = new Runnable() {
4726 bindAllApplications(mTmpAppsList);
4727 mTmpAppsList = null;
4732 * Add the icons for all apps.
4734 * Implementation of the method from LauncherModel.Callbacks.
4736 public void bindAllApplications(final ArrayList<AppInfo> apps) {
4737 if (waitUntilResume(mBindAllApplicationsRunnable, true)) {
4738 mTmpAppsList = apps;
4742 if (mAppsView != null) {
4743 mAppsView.setApps(apps);
4745 if (mLauncherCallbacks != null) {
4746 mLauncherCallbacks.bindAllApplications(apps);
4751 * A package was updated.
4753 * Implementation of the method from LauncherModel.Callbacks.
4755 public void bindAppsUpdated(final ArrayList<AppInfo> apps) {
4756 Runnable r = new Runnable() {
4758 bindAppsUpdated(apps);
4761 if (waitUntilResume(r)) {
4765 if (mAppsView != null) {
4766 mAppsView.updateApps(apps);
4771 public void bindWidgetsRestored(final ArrayList<LauncherAppWidgetInfo> widgets) {
4772 Runnable r = new Runnable() {
4774 bindWidgetsRestored(widgets);
4777 if (waitUntilResume(r)) {
4780 mWorkspace.widgetsRestored(widgets);
4784 * Some shortcuts were updated in the background.
4786 * Implementation of the method from LauncherModel.Callbacks.
4789 public void bindShortcutsChanged(final ArrayList<ShortcutInfo> updated,
4790 final ArrayList<ShortcutInfo> removed, final UserHandleCompat user) {
4791 Runnable r = new Runnable() {
4793 bindShortcutsChanged(updated, removed, user);
4796 if (waitUntilResume(r)) {
4800 if (!updated.isEmpty()) {
4801 mWorkspace.updateShortcuts(updated);
4804 if (!removed.isEmpty()) {
4805 HashSet<ComponentName> removedComponents = new HashSet<ComponentName>();
4806 for (ShortcutInfo si : removed) {
4807 removedComponents.add(si.getTargetComponent());
4809 mWorkspace.removeItemsByComponentName(removedComponents, user);
4810 // Notify the drag controller
4811 mDragController.onAppsRemoved(new ArrayList<String>(), removedComponents);
4816 * Update the state of a package, typically related to install state.
4818 * Implementation of the method from LauncherModel.Callbacks.
4821 public void bindRestoreItemsChange(final HashSet<ItemInfo> updates) {
4822 Runnable r = new Runnable() {
4824 bindRestoreItemsChange(updates);
4827 if (waitUntilResume(r)) {
4831 mWorkspace.updateRestoreItems(updates);
4835 * A package was uninstalled. We take both the super set of packageNames
4836 * in addition to specific applications to remove, the reason being that
4837 * this can be called when a package is updated as well. In that scenario,
4838 * we only remove specific components from the workspace, where as
4839 * package-removal should clear all items by package name.
4841 * @param reason if non-zero, the icons are not permanently removed, rather marked as disabled.
4842 * Implementation of the method from LauncherModel.Callbacks.
4845 public void bindComponentsRemoved(final ArrayList<String> packageNames,
4846 final ArrayList<AppInfo> appInfos, final UserHandleCompat user, final int reason) {
4847 Runnable r = new Runnable() {
4849 bindComponentsRemoved(packageNames, appInfos, user, reason);
4852 if (waitUntilResume(r)) {
4857 HashSet<ComponentName> removedComponents = new HashSet<ComponentName>();
4858 for (AppInfo info : appInfos) {
4859 removedComponents.add(info.componentName);
4861 if (packageNames != null && !packageNames.isEmpty()) {
4862 mWorkspace.removeItemsByPackageName(packageNames, user);
4864 if (!removedComponents.isEmpty()) {
4865 mWorkspace.removeItemsByComponentName(removedComponents, user);
4867 // Notify the drag controller
4868 mDragController.onAppsRemoved(packageNames, removedComponents);
4871 mWorkspace.disableShortcutsByPackageName(packageNames, user, reason);
4875 if (mAppsView != null) {
4876 mAppsView.removeApps(appInfos);
4881 * A package has become unavailable.
4883 * Implementation of the method from LauncherModel.Callbacks.
4885 public void bindComponentsUnavailable(final ArrayList<String> packageNames,
4886 final ArrayList<AppInfo> appInfos) {
4887 if (!packageNames.isEmpty()) {
4888 mWorkspace.updateUnavailableItemsByPackageName(packageNames);
4890 HashSet<ComponentName> cns = new HashSet<>();
4891 for (AppInfo appInfo : appInfos) {
4892 cns.add(appInfo.componentName);
4894 // Notify the drag controller
4895 mDragController.onAppsRemoved(packageNames, cns);
4896 mAppsView.removeApps(appInfos);
4900 * A package has become unavailable.
4902 * Implementation of the method from LauncherModel.Callbacks.
4904 public void bindComponentsAvailable(final ArrayList<ItemInfo> itemInfos) {
4905 if (!itemInfos.isEmpty()) {
4906 mWorkspace.updateAvailableItems(itemInfos);
4911 * A number of packages were updated.
4913 private ArrayList<Object> mWidgetsAndShortcuts;
4914 private Runnable mBindPackagesUpdatedRunnable = new Runnable() {
4916 bindAllPackages(mWidgetsModel);
4920 public void bindPackagesUpdated(final ArrayList<Object> widgetsAndShortcuts) {
4921 if (waitUntilResume(mBindPackagesUpdatedRunnable, true)) {
4922 mWidgetsAndShortcuts = widgetsAndShortcuts;
4928 public void bindAllPackages(final WidgetsModel model) {
4929 if (waitUntilResume(mBindPackagesUpdatedRunnable, true)) {
4930 mWidgetsModel = model;
4934 if (mWidgetsView != null && model != null) {
4935 mWidgetsView.addWidgets(model);
4936 mWidgetsModel = null;
4940 private int mapConfigurationOriActivityInfoOri(int configOri) {
4941 final Display d = getWindowManager().getDefaultDisplay();
4942 int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
4943 switch (d.getRotation()) {
4944 case Surface.ROTATION_0:
4945 case Surface.ROTATION_180:
4946 // We are currently in the same basic orientation as the natural orientation
4947 naturalOri = configOri;
4949 case Surface.ROTATION_90:
4950 case Surface.ROTATION_270:
4951 // We are currently in the other basic orientation to the natural orientation
4952 naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
4953 Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
4958 ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
4959 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
4960 ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
4961 ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
4963 // Since the map starts at portrait, we need to offset if this device's natural orientation
4965 int indexOffset = 0;
4966 if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
4969 return oriMap[(d.getRotation() + indexOffset) % 4];
4972 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
4973 public void lockScreenOrientation() {
4974 if (mRotationEnabled) {
4975 if (Utilities.ATLEAST_JB_MR2) {
4976 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
4978 setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
4979 .getConfiguration().orientation));
4984 public void unlockScreenOrientation(boolean immediate) {
4985 if (mRotationEnabled) {
4987 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
4989 mHandler.postDelayed(new Runnable() {
4991 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
4993 }, mRestoreScreenOrientationDelay);
4998 protected boolean isLauncherPreinstalled() {
4999 if (mLauncherCallbacks != null) {
5000 return mLauncherCallbacks.isLauncherPreinstalled();
5002 PackageManager pm = getPackageManager();
5004 ApplicationInfo ai = pm.getApplicationInfo(getComponentName().getPackageName(), 0);
5005 if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5010 } catch (NameNotFoundException e) {
5011 e.printStackTrace();
5017 * This method indicates whether or not we should suggest default wallpaper dimensions
5018 * when our wallpaper cropper was not yet used to set a wallpaper.
5020 protected boolean overrideWallpaperDimensions() {
5021 if (mLauncherCallbacks != null) {
5022 return mLauncherCallbacks.overrideWallpaperDimensions();
5028 * To be overridden by subclasses to indicate that there is an activity to launch
5029 * before showing the standard launcher experience.
5031 protected boolean hasFirstRunActivity() {
5032 if (mLauncherCallbacks != null) {
5033 return mLauncherCallbacks.hasFirstRunActivity();
5039 * To be overridden by subclasses to launch any first run activity
5041 protected Intent getFirstRunActivity() {
5042 if (mLauncherCallbacks != null) {
5043 return mLauncherCallbacks.getFirstRunActivity();
5048 private boolean shouldRunFirstRunActivity() {
5049 return !ActivityManager.isRunningInTestHarness() &&
5050 !mSharedPrefs.getBoolean(FIRST_RUN_ACTIVITY_DISPLAYED, false);
5053 protected boolean hasRunFirstRunActivity() {
5054 return mSharedPrefs.getBoolean(FIRST_RUN_ACTIVITY_DISPLAYED, false);
5057 public boolean showFirstRunActivity() {
5058 if (shouldRunFirstRunActivity() &&
5059 hasFirstRunActivity()) {
5060 Intent firstRunIntent = getFirstRunActivity();
5061 if (firstRunIntent != null) {
5062 startActivity(firstRunIntent);
5063 markFirstRunActivityShown();
5070 private void markFirstRunActivityShown() {
5071 SharedPreferences.Editor editor = mSharedPrefs.edit();
5072 editor.putBoolean(FIRST_RUN_ACTIVITY_DISPLAYED, true);
5077 * To be overridden by subclasses to indicate that there is an in-activity full-screen intro
5078 * screen that must be displayed and dismissed.
5080 protected boolean hasDismissableIntroScreen() {
5081 if (mLauncherCallbacks != null) {
5082 return mLauncherCallbacks.hasDismissableIntroScreen();
5088 * Full screen intro screen to be shown and dismissed before the launcher can be used.
5090 protected View getIntroScreen() {
5091 if (mLauncherCallbacks != null) {
5092 return mLauncherCallbacks.getIntroScreen();
5098 * To be overriden by subclasses to indicate whether the in-activity intro screen has been
5099 * dismissed. This method is ignored if #hasDismissableIntroScreen returns false.
5101 private boolean shouldShowIntroScreen() {
5102 return hasDismissableIntroScreen() &&
5103 !mSharedPrefs.getBoolean(INTRO_SCREEN_DISMISSED, false);
5106 protected void showIntroScreen() {
5107 View introScreen = getIntroScreen();
5108 changeWallpaperVisiblity(false);
5109 if (introScreen != null) {
5110 mDragLayer.showOverlayView(introScreen);
5112 if (mLauncherOverlayContainer != null) {
5113 mLauncherOverlayContainer.setVisibility(View.INVISIBLE);
5117 public void dismissIntroScreen() {
5118 markIntroScreenDismissed();
5119 if (showFirstRunActivity()) {
5120 // We delay hiding the intro view until the first run activity is showing. This
5122 mWorkspace.postDelayed(new Runnable() {
5125 mDragLayer.dismissOverlayView();
5126 if (mLauncherOverlayContainer != null) {
5127 mLauncherOverlayContainer.setVisibility(View.VISIBLE);
5129 showFirstRunClings();
5131 }, ACTIVITY_START_DELAY);
5133 mDragLayer.dismissOverlayView();
5134 if (mLauncherOverlayContainer != null) {
5135 mLauncherOverlayContainer.setVisibility(View.VISIBLE);
5137 showFirstRunClings();
5139 changeWallpaperVisiblity(true);
5142 private void markIntroScreenDismissed() {
5143 SharedPreferences.Editor editor = mSharedPrefs.edit();
5144 editor.putBoolean(INTRO_SCREEN_DISMISSED, true);
5148 @Thunk void showFirstRunClings() {
5149 // The two first run cling paths are mutually exclusive, if the launcher is preinstalled
5150 // on the device, then we always show the first run cling experience (or if there is no
5151 // launcher2). Otherwise, we prompt the user upon started for migration
5152 LauncherClings launcherClings = new LauncherClings(this);
5153 if (launcherClings.shouldShowFirstRunOrMigrationClings()) {
5154 mClings = launcherClings;
5155 if (mModel.canMigrateFromOldLauncherDb(this)) {
5156 launcherClings.showMigrationCling();
5158 launcherClings.showLongPressCling(true);
5163 void showWorkspaceSearchAndHotseat() {
5164 if (mWorkspace != null) mWorkspace.setAlpha(1f);
5165 if (mHotseat != null) mHotseat.setAlpha(1f);
5166 if (mPageIndicators != null) mPageIndicators.setAlpha(1f);
5167 if (mSearchDropTargetBar != null) mSearchDropTargetBar.animateToState(
5168 SearchDropTargetBar.State.SEARCH_BAR, 0);
5171 void hideWorkspaceSearchAndHotseat() {
5172 if (mWorkspace != null) mWorkspace.setAlpha(0f);
5173 if (mHotseat != null) mHotseat.setAlpha(0f);
5174 if (mPageIndicators != null) mPageIndicators.setAlpha(0f);
5175 if (mSearchDropTargetBar != null) mSearchDropTargetBar.animateToState(
5176 SearchDropTargetBar.State.INVISIBLE, 0);
5179 // TODO: These method should be a part of LauncherSearchCallback
5180 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
5181 public ItemInfo createAppDragInfo(Intent appLaunchIntent) {
5182 // Called from search suggestion
5183 UserHandleCompat user = null;
5184 if (Utilities.ATLEAST_LOLLIPOP) {
5185 UserHandle userHandle = appLaunchIntent.getParcelableExtra(Intent.EXTRA_USER);
5186 if (userHandle != null) {
5187 user = UserHandleCompat.fromUser(userHandle);
5190 return createAppDragInfo(appLaunchIntent, user);
5193 // TODO: This method should be a part of LauncherSearchCallback
5194 public ItemInfo createAppDragInfo(Intent intent, UserHandleCompat user) {
5196 user = UserHandleCompat.myUserHandle();
5199 // Called from search suggestion, add the profile extra to the intent to ensure that we
5200 // can launch it correctly
5201 LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this);
5202 LauncherActivityInfoCompat activityInfo = launcherApps.resolveActivity(intent, user);
5203 if (activityInfo == null) {
5206 return new AppInfo(this, activityInfo, user, mIconCache);
5209 // TODO: This method should be a part of LauncherSearchCallback
5210 public ItemInfo createShortcutDragInfo(Intent shortcutIntent, CharSequence caption,
5212 return new ShortcutInfo(shortcutIntent, caption, caption, icon,
5213 UserHandleCompat.myUserHandle());
5216 // TODO: This method should be a part of LauncherSearchCallback
5217 public void startDrag(View dragView, ItemInfo dragInfo, DragSource source) {
5218 dragView.setTag(dragInfo);
5219 mWorkspace.onExternalDragStartedWithItem(dragView);
5220 mWorkspace.beginExternalDragShared(dragView, source);
5223 protected void moveWorkspaceToDefaultScreen() {
5224 mWorkspace.moveToDefaultScreen(false);
5228 public void onPageSwitch(View newPage, int newPageIndex) {
5229 if (mLauncherCallbacks != null) {
5230 mLauncherCallbacks.onPageSwitch(newPage, newPageIndex);
5235 * Returns a FastBitmapDrawable with the icon, accurately sized.
5237 public FastBitmapDrawable createIconDrawable(Bitmap icon) {
5238 FastBitmapDrawable d = new FastBitmapDrawable(icon);
5239 d.setFilterBitmap(true);
5240 resizeIconDrawable(d);
5245 * Resizes an icon drawable to the correct icon size.
5247 public void resizeIconDrawable(Drawable icon) {
5248 icon.setBounds(0, 0, mDeviceProfile.iconSizePx, mDeviceProfile.iconSizePx);
5252 * Prints out out state for debugging.
5254 public void dumpState() {
5255 Log.d(TAG, "BEGIN launcher3 dump state for launcher " + this);
5256 Log.d(TAG, "mSavedState=" + mSavedState);
5257 Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
5258 Log.d(TAG, "mRestoring=" + mRestoring);
5259 Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
5260 Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
5261 Log.d(TAG, "sFolders.size=" + sFolders.size());
5263 // TODO(hyunyoungs): add mWidgetsView.dumpState(); or mWidgetsModel.dumpState();
5265 Log.d(TAG, "END launcher3 dump state");
5269 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
5270 super.dump(prefix, fd, writer, args);
5271 synchronized (sDumpLogs) {
5272 writer.println(" ");
5273 writer.println("Debug logs: ");
5274 for (int i = 0; i < sDumpLogs.size(); i++) {
5275 writer.println(" " + sDumpLogs.get(i));
5278 if (mLauncherCallbacks != null) {
5279 mLauncherCallbacks.dump(prefix, fd, writer, args);
5283 public static void dumpDebugLogsToConsole() {
5284 if (DEBUG_DUMP_LOG) {
5285 synchronized (sDumpLogs) {
5287 Log.d(TAG, "*********************");
5288 Log.d(TAG, "Launcher debug logs: ");
5289 for (int i = 0; i < sDumpLogs.size(); i++) {
5290 Log.d(TAG, " " + sDumpLogs.get(i));
5292 Log.d(TAG, "*********************");
5298 public static void addDumpLog(String tag, String log, boolean debugLog) {
5299 addDumpLog(tag, log, null, debugLog);
5302 public static void addDumpLog(String tag, String log, Exception e, boolean debugLog) {
5310 if (DEBUG_DUMP_LOG) {
5311 sDateStamp.setTime(System.currentTimeMillis());
5312 synchronized (sDumpLogs) {
5313 sDumpLogs.add(sDateFormat.format(sDateStamp) + ": " + tag + ", " + log
5314 + (e == null ? "" : (", Exception: " + e)));
5319 public static CustomAppWidget getCustomAppWidget(String name) {
5320 return sCustomAppWidgets.get(name);
5323 public static HashMap<String, CustomAppWidget> getCustomAppWidgets() {
5324 return sCustomAppWidgets;
5327 public void dumpLogsToLocalData() {
5328 if (DEBUG_DUMP_LOG) {
5329 new AsyncTask<Void, Void, Void>() {
5330 public Void doInBackground(Void ... args) {
5331 boolean success = false;
5332 sDateStamp.setTime(sRunStart);
5333 String FILENAME = sDateStamp.getMonth() + "-"
5334 + sDateStamp.getDay() + "_"
5335 + sDateStamp.getHours() + "-"
5336 + sDateStamp.getMinutes() + "_"
5337 + sDateStamp.getSeconds() + ".txt";
5339 FileOutputStream fos = null;
5340 File outFile = null;
5342 outFile = new File(getFilesDir(), FILENAME);
5343 outFile.createNewFile();
5344 fos = new FileOutputStream(outFile);
5345 } catch (Exception e) {
5346 e.printStackTrace();
5349 PrintWriter writer = new PrintWriter(fos);
5351 writer.println(" ");
5352 writer.println("Debug logs: ");
5353 synchronized (sDumpLogs) {
5354 for (int i = 0; i < sDumpLogs.size(); i++) {
5355 writer.println(" " + sDumpLogs.get(i));
5365 } catch (IOException e) {
5366 e.printStackTrace();
5370 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
5374 private void setupSearchBar(Context context) {
5375 mIsDrawerSearchBarEnabled = SettingsProvider.getBoolean(context,
5376 SettingsProvider.SETTINGS_UI_DRAWER_SEARCH,
5377 R.bool.preferences_interface_homescreen_search_default);
5379 if (mIsDrawerSearchBarEnabled) {
5380 if (mLauncherCallbacks != null
5381 && mLauncherCallbacks.getAllAppsSearchBarController() != null) {
5383 .setSearchBarController(mLauncherCallbacks.getAllAppsSearchBarController());
5385 mAppsView.setSearchBarController(mAppsView.newDefaultAppSearchController());
5388 mAppsView.setSearchBarController(null);
5389 mAppsView.setHasSearchBar(mIsDrawerSearchBarEnabled);
5390 mAppsView.setSearchBarContainerViewVisibility(
5391 mIsDrawerSearchBarEnabled ? View.VISIBLE : View.GONE);
5392 mAppsView.updateBackgroundAndPaddings();
5396 class SettingsPanelSlideListener extends VerticalSlidingPanel.SimplePanelSlideListener {
5397 ImageView mAnimatedArrow;
5399 public SettingsPanelSlideListener() {
5401 mAnimatedArrow = (ImageView) mOverviewPanel.findViewById(R.id.settings_drag_arrow);
5405 public void onPanelCollapsed(View panel) {
5406 mAnimatedArrow.setBackgroundResource(R.drawable.transition_arrow_reverse);
5408 AnimationDrawable frameAnimation = (AnimationDrawable) mAnimatedArrow.getBackground();
5409 frameAnimation.start();
5413 public void onPanelExpanded(View panel) {
5414 mAnimatedArrow.setBackgroundResource(R.drawable.transition_arrow);
5416 AnimationDrawable frameAnimation = (AnimationDrawable) mAnimatedArrow.getBackground();
5417 frameAnimation.start();
5421 public void onPanelShown(View panel) {
5422 mAnimatedArrow.setBackgroundResource(R.drawable.transition_arrow_reverse);
5424 AnimationDrawable frameAnimation = (AnimationDrawable) mAnimatedArrow.getBackground();
5425 frameAnimation.start();
5430 interface DebugIntents {
5431 static final String DELETE_DATABASE = "com.android.launcher3.action.DELETE_DATABASE";
5432 static final String MIGRATE_DATABASE = "com.android.launcher3.action.MIGRATE_DATABASE";