1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.launcher3.dragndrop; 18 19 import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_PIN_WIDGETS; 20 import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ADD_EXTERNAL_ITEM_BACK; 21 import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ADD_EXTERNAL_ITEM_CANCELLED; 22 import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ADD_EXTERNAL_ITEM_DRAGGED; 23 import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ADD_EXTERNAL_ITEM_PLACED_AUTOMATICALLY; 24 import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ADD_EXTERNAL_ITEM_START; 25 import static com.android.launcher3.util.Executors.MODEL_EXECUTOR; 26 27 import android.annotation.TargetApi; 28 import android.app.ActivityOptions; 29 import android.appwidget.AppWidgetManager; 30 import android.appwidget.AppWidgetProviderInfo; 31 import android.content.ClipData; 32 import android.content.ClipDescription; 33 import android.content.Intent; 34 import android.content.pm.LauncherApps.PinItemRequest; 35 import android.content.pm.ShortcutInfo; 36 import android.content.res.Configuration; 37 import android.graphics.Canvas; 38 import android.graphics.Point; 39 import android.graphics.PointF; 40 import android.graphics.Rect; 41 import android.os.AsyncTask; 42 import android.os.Build; 43 import android.os.Bundle; 44 import android.text.TextUtils; 45 import android.view.MotionEvent; 46 import android.view.View; 47 import android.view.View.DragShadowBuilder; 48 import android.view.View.OnLongClickListener; 49 import android.view.View.OnTouchListener; 50 import android.view.WindowManager; 51 import android.view.accessibility.AccessibilityEvent; 52 import android.view.accessibility.AccessibilityManager; 53 import android.widget.TextView; 54 55 import com.android.launcher3.BaseActivity; 56 import com.android.launcher3.InvariantDeviceProfile; 57 import com.android.launcher3.Launcher; 58 import com.android.launcher3.LauncherAppState; 59 import com.android.launcher3.R; 60 import com.android.launcher3.logging.StatsLogManager; 61 import com.android.launcher3.model.ItemInstallQueue; 62 import com.android.launcher3.model.WidgetItem; 63 import com.android.launcher3.model.data.ItemInfo; 64 import com.android.launcher3.pm.PinRequestHelper; 65 import com.android.launcher3.util.SystemUiController; 66 import com.android.launcher3.views.AbstractSlideInView; 67 import com.android.launcher3.views.BaseDragLayer; 68 import com.android.launcher3.widget.AddItemWidgetsBottomSheet; 69 import com.android.launcher3.widget.LauncherAppWidgetHost; 70 import com.android.launcher3.widget.LauncherAppWidgetProviderInfo; 71 import com.android.launcher3.widget.NavigableAppWidgetHostView; 72 import com.android.launcher3.widget.PendingAddShortcutInfo; 73 import com.android.launcher3.widget.PendingAddWidgetInfo; 74 import com.android.launcher3.widget.WidgetCell; 75 import com.android.launcher3.widget.WidgetCellPreview; 76 import com.android.launcher3.widget.WidgetImageView; 77 import com.android.launcher3.widget.WidgetManagerHelper; 78 79 import java.util.function.Supplier; 80 81 /** 82 * Activity to show pin widget dialog. 83 */ 84 @TargetApi(Build.VERSION_CODES.O) 85 public class AddItemActivity extends BaseActivity 86 implements OnLongClickListener, OnTouchListener, AbstractSlideInView.OnCloseListener { 87 88 private static final int SHADOW_SIZE = 10; 89 90 private static final int REQUEST_BIND_APPWIDGET = 1; 91 private static final String STATE_EXTRA_WIDGET_ID = "state.widget.id"; 92 93 private final PointF mLastTouchPos = new PointF(); 94 95 private PinItemRequest mRequest; 96 private LauncherAppState mApp; 97 private InvariantDeviceProfile mIdp; 98 private BaseDragLayer<AddItemActivity> mDragLayer; 99 private AddItemWidgetsBottomSheet mSlideInView; 100 private AccessibilityManager mAccessibilityManager; 101 102 private WidgetCell mWidgetCell; 103 104 // Widget request specific options. 105 private LauncherAppWidgetHost mAppWidgetHost; 106 private WidgetManagerHelper mAppWidgetManager; 107 private int mPendingBindWidgetId; 108 private Bundle mWidgetOptions; 109 110 private boolean mFinishOnPause = false; 111 112 @Override onCreate(Bundle savedInstanceState)113 protected void onCreate(Bundle savedInstanceState) { 114 super.onCreate(savedInstanceState); 115 116 mRequest = PinRequestHelper.getPinItemRequest(getIntent()); 117 if (mRequest == null) { 118 finish(); 119 return; 120 } 121 122 mApp = LauncherAppState.getInstance(this); 123 mIdp = mApp.getInvariantDeviceProfile(); 124 125 // Use the application context to get the device profile, as in multiwindow-mode, the 126 // confirmation activity might be rotated. 127 mDeviceProfile = mIdp.getDeviceProfile(getApplicationContext()); 128 129 setContentView(R.layout.add_item_confirmation_activity); 130 // Set flag to allow activity to draw over navigation and status bar. 131 getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, 132 WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); 133 mDragLayer = findViewById(R.id.add_item_drag_layer); 134 mDragLayer.recreateControllers(); 135 mWidgetCell = findViewById(R.id.widget_cell); 136 mAccessibilityManager = 137 getApplicationContext().getSystemService(AccessibilityManager.class); 138 139 if (mRequest.getRequestType() == PinItemRequest.REQUEST_TYPE_SHORTCUT) { 140 setupShortcut(); 141 } else { 142 if (!setupWidget()) { 143 // TODO: show error toast? 144 finish(); 145 } 146 } 147 148 WidgetCellPreview previewContainer = mWidgetCell.findViewById( 149 R.id.widget_preview_container); 150 previewContainer.setOnTouchListener(this); 151 previewContainer.setOnLongClickListener(this); 152 153 // savedInstanceState is null when the activity is created the first time (i.e., avoids 154 // duplicate logging during rotation) 155 if (savedInstanceState == null) { 156 logCommand(LAUNCHER_ADD_EXTERNAL_ITEM_START); 157 } 158 159 TextView widgetAppName = findViewById(R.id.widget_appName); 160 widgetAppName.setText(getApplicationInfo().labelRes); 161 162 mSlideInView = findViewById(R.id.add_item_bottom_sheet); 163 mSlideInView.addOnCloseListener(this); 164 mSlideInView.show(); 165 setupNavBarColor(); 166 } 167 168 @Override onTouch(View view, MotionEvent motionEvent)169 public boolean onTouch(View view, MotionEvent motionEvent) { 170 mLastTouchPos.set(motionEvent.getX(), motionEvent.getY()); 171 return false; 172 } 173 174 @Override onLongClick(View view)175 public boolean onLongClick(View view) { 176 // Find the position of the preview relative to the touch location. 177 WidgetImageView img = mWidgetCell.getWidgetView(); 178 NavigableAppWidgetHostView appWidgetHostView = mWidgetCell.getAppWidgetHostViewPreview(); 179 180 // If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and 181 // we abort the drag. 182 if (img.getDrawable() == null && appWidgetHostView == null) { 183 return false; 184 } 185 186 final Rect bounds; 187 // Start home and pass the draw request params 188 final PinItemDragListener listener; 189 if (appWidgetHostView != null) { 190 bounds = new Rect(); 191 appWidgetHostView.getSourceVisualDragBounds(bounds); 192 bounds.offset(appWidgetHostView.getLeft() - (int) mLastTouchPos.x, 193 appWidgetHostView.getTop() - (int) mLastTouchPos.y); 194 listener = new PinItemDragListener(mRequest, bounds, 195 appWidgetHostView.getMeasuredWidth(), appWidgetHostView.getMeasuredWidth()); 196 } else { 197 bounds = img.getBitmapBounds(); 198 bounds.offset(img.getLeft() - (int) mLastTouchPos.x, 199 img.getTop() - (int) mLastTouchPos.y); 200 listener = new PinItemDragListener(mRequest, bounds, 201 img.getDrawable().getIntrinsicWidth(), img.getWidth()); 202 } 203 204 // Start a system drag and drop. We use a transparent bitmap as preview for system drag 205 // as the preview is handled internally by launcher. 206 ClipDescription description = new ClipDescription("", new String[]{listener.getMimeType()}); 207 ClipData data = new ClipData(description, new ClipData.Item("")); 208 view.startDragAndDrop(data, new DragShadowBuilder(view) { 209 210 @Override 211 public void onDrawShadow(Canvas canvas) { } 212 213 @Override 214 public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) { 215 outShadowSize.set(SHADOW_SIZE, SHADOW_SIZE); 216 outShadowTouchPoint.set(SHADOW_SIZE / 2, SHADOW_SIZE / 2); 217 } 218 }, null, View.DRAG_FLAG_GLOBAL); 219 220 Intent homeIntent = new Intent(Intent.ACTION_MAIN) 221 .addCategory(Intent.CATEGORY_HOME) 222 .setPackage(getPackageName()) 223 .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 224 Launcher.ACTIVITY_TRACKER.registerCallback(listener); 225 startActivity(homeIntent, 226 ActivityOptions.makeCustomAnimation(this, 0, android.R.anim.fade_out) 227 .toBundle()); 228 logCommand(LAUNCHER_ADD_EXTERNAL_ITEM_DRAGGED); 229 mFinishOnPause = true; 230 return false; 231 } 232 233 @Override onPause()234 protected void onPause() { 235 super.onPause(); 236 if (mFinishOnPause) { 237 finish(); 238 } 239 } 240 setupShortcut()241 private void setupShortcut() { 242 PinShortcutRequestActivityInfo shortcutInfo = 243 new PinShortcutRequestActivityInfo(mRequest, this); 244 mWidgetCell.getWidgetView().setTag(new PendingAddShortcutInfo(shortcutInfo)); 245 applyWidgetItemAsync( 246 () -> new WidgetItem(shortcutInfo, mApp.getIconCache(), getPackageManager())); 247 } 248 setupWidget()249 private boolean setupWidget() { 250 LauncherAppWidgetProviderInfo widgetInfo = LauncherAppWidgetProviderInfo 251 .fromProviderInfo(this, mRequest.getAppWidgetProviderInfo(this)); 252 if (widgetInfo.minSpanX > mIdp.numColumns || widgetInfo.minSpanY > mIdp.numRows) { 253 // Cannot add widget 254 return false; 255 } 256 mWidgetCell.setRemoteViewsPreview(PinItemDragListener.getPreview(mRequest)); 257 258 mAppWidgetManager = new WidgetManagerHelper(this); 259 mAppWidgetHost = new LauncherAppWidgetHost(this); 260 261 PendingAddWidgetInfo pendingInfo = 262 new PendingAddWidgetInfo(widgetInfo, CONTAINER_PIN_WIDGETS); 263 pendingInfo.spanX = Math.min(mIdp.numColumns, widgetInfo.spanX); 264 pendingInfo.spanY = Math.min(mIdp.numRows, widgetInfo.spanY); 265 mWidgetOptions = pendingInfo.getDefaultSizeOptions(this); 266 mWidgetCell.getWidgetView().setTag(pendingInfo); 267 268 applyWidgetItemAsync(() -> new WidgetItem(widgetInfo, mIdp, mApp.getIconCache())); 269 return true; 270 } 271 applyWidgetItemAsync(final Supplier<WidgetItem> itemProvider)272 private void applyWidgetItemAsync(final Supplier<WidgetItem> itemProvider) { 273 new AsyncTask<Void, Void, WidgetItem>() { 274 @Override 275 protected WidgetItem doInBackground(Void... voids) { 276 return itemProvider.get(); 277 } 278 279 @Override 280 protected void onPostExecute(WidgetItem item) { 281 mWidgetCell.setPreviewSize(item); 282 mWidgetCell.applyFromCellItem(item, mApp.getWidgetCache()); 283 mWidgetCell.ensurePreview(); 284 } 285 }.executeOnExecutor(MODEL_EXECUTOR); 286 // TODO: Create a worker looper executor and reuse that everywhere. 287 } 288 289 /** 290 * Called when the cancel button is clicked. 291 */ onCancelClick(View v)292 public void onCancelClick(View v) { 293 logCommand(LAUNCHER_ADD_EXTERNAL_ITEM_CANCELLED); 294 mSlideInView.close(/* animate= */ true); 295 } 296 297 /** 298 * Called when place-automatically button is clicked. 299 */ onPlaceAutomaticallyClick(View v)300 public void onPlaceAutomaticallyClick(View v) { 301 if (mRequest.getRequestType() == PinItemRequest.REQUEST_TYPE_SHORTCUT) { 302 ShortcutInfo shortcutInfo = mRequest.getShortcutInfo(); 303 ItemInstallQueue.INSTANCE.get(this).queueItem(shortcutInfo); 304 logCommand(LAUNCHER_ADD_EXTERNAL_ITEM_PLACED_AUTOMATICALLY); 305 mRequest.accept(); 306 CharSequence label = shortcutInfo.getLongLabel(); 307 if (TextUtils.isEmpty(label)) { 308 label = shortcutInfo.getShortLabel(); 309 } 310 sendWidgetAddedToScreenAccessibilityEvent(label.toString()); 311 mSlideInView.close(/* animate= */ true); 312 return; 313 } 314 315 mPendingBindWidgetId = mAppWidgetHost.allocateAppWidgetId(); 316 AppWidgetProviderInfo widgetProviderInfo = mRequest.getAppWidgetProviderInfo(this); 317 boolean success = mAppWidgetManager.bindAppWidgetIdIfAllowed( 318 mPendingBindWidgetId, widgetProviderInfo, mWidgetOptions); 319 if (success) { 320 sendWidgetAddedToScreenAccessibilityEvent(widgetProviderInfo.label); 321 acceptWidget(mPendingBindWidgetId); 322 return; 323 } 324 325 // request bind widget 326 mAppWidgetHost.startBindFlow(this, mPendingBindWidgetId, 327 mRequest.getAppWidgetProviderInfo(this), REQUEST_BIND_APPWIDGET); 328 } 329 acceptWidget(int widgetId)330 private void acceptWidget(int widgetId) { 331 ItemInstallQueue.INSTANCE.get(this) 332 .queueItem(mRequest.getAppWidgetProviderInfo(this), widgetId); 333 mWidgetOptions.putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId); 334 mRequest.accept(mWidgetOptions); 335 logCommand(LAUNCHER_ADD_EXTERNAL_ITEM_PLACED_AUTOMATICALLY); 336 mSlideInView.close(/* animate= */ true); 337 } 338 339 @Override onBackPressed()340 public void onBackPressed() { 341 logCommand(LAUNCHER_ADD_EXTERNAL_ITEM_BACK); 342 mSlideInView.close(/* animate= */ true); 343 } 344 345 @Override onActivityResult(int requestCode, int resultCode, Intent data)346 public void onActivityResult(int requestCode, int resultCode, Intent data) { 347 if (requestCode == REQUEST_BIND_APPWIDGET) { 348 int widgetId = data != null 349 ? data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mPendingBindWidgetId) 350 : mPendingBindWidgetId; 351 if (resultCode == RESULT_OK) { 352 acceptWidget(widgetId); 353 } else { 354 // Simply wait it out. 355 mAppWidgetHost.deleteAppWidgetId(widgetId); 356 mPendingBindWidgetId = -1; 357 } 358 return; 359 } 360 super.onActivityResult(requestCode, resultCode, data); 361 } 362 363 @Override onSaveInstanceState(Bundle outState)364 protected void onSaveInstanceState(Bundle outState) { 365 super.onSaveInstanceState(outState); 366 outState.putInt(STATE_EXTRA_WIDGET_ID, mPendingBindWidgetId); 367 } 368 369 @Override onRestoreInstanceState(Bundle savedInstanceState)370 protected void onRestoreInstanceState(Bundle savedInstanceState) { 371 super.onRestoreInstanceState(savedInstanceState); 372 mPendingBindWidgetId = savedInstanceState 373 .getInt(STATE_EXTRA_WIDGET_ID, mPendingBindWidgetId); 374 } 375 376 @Override getDragLayer()377 public BaseDragLayer getDragLayer() { 378 return mDragLayer; 379 } 380 381 @Override onSlideInViewClosed()382 public void onSlideInViewClosed() { 383 finish(); 384 } 385 setupNavBarColor()386 protected void setupNavBarColor() { 387 boolean isSheetDark = (getApplicationContext().getResources().getConfiguration().uiMode 388 & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES; 389 getSystemUiController().updateUiState( 390 SystemUiController.UI_STATE_BASE_WINDOW, 391 isSheetDark ? SystemUiController.FLAG_DARK_NAV : SystemUiController.FLAG_LIGHT_NAV); 392 } 393 sendWidgetAddedToScreenAccessibilityEvent(String widgetName)394 private void sendWidgetAddedToScreenAccessibilityEvent(String widgetName) { 395 if (mAccessibilityManager.isEnabled()) { 396 AccessibilityEvent event = 397 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_ANNOUNCEMENT); 398 event.setContentDescription( 399 getApplicationContext().getResources().getString( 400 R.string.added_to_home_screen_accessibility_text, widgetName)); 401 mAccessibilityManager.sendAccessibilityEvent(event); 402 } 403 } 404 logCommand(StatsLogManager.EventEnum command)405 private void logCommand(StatsLogManager.EventEnum command) { 406 getStatsLogManager().logger() 407 .withItemInfo((ItemInfo) mWidgetCell.getWidgetView().getTag()) 408 .log(command); 409 } 410 } 411