1 /* 2 * Copyright (C) 2011 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.nfc.beam; 18 19 import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS; 20 21 import android.animation.Animator; 22 import android.animation.AnimatorSet; 23 import android.animation.ObjectAnimator; 24 import android.animation.PropertyValuesHolder; 25 import android.animation.TimeAnimator; 26 import android.app.ActivityManager; 27 import android.app.StatusBarManager; 28 import android.content.BroadcastReceiver; 29 import android.content.Context; 30 import android.content.Intent; 31 import android.content.IntentFilter; 32 import android.content.pm.ActivityInfo; 33 import android.content.res.Configuration; 34 import android.graphics.Bitmap; 35 import android.graphics.Matrix; 36 import android.graphics.PixelFormat; 37 import android.graphics.Rect; 38 import android.graphics.SurfaceTexture; 39 import android.os.AsyncTask; 40 import android.os.Binder; 41 import android.os.IBinder; 42 import android.util.DisplayMetrics; 43 import android.util.Log; 44 import android.view.ActionMode; 45 import android.view.Display; 46 import android.view.KeyEvent; 47 import android.view.LayoutInflater; 48 import android.view.Menu; 49 import android.view.MenuItem; 50 import android.view.MotionEvent; 51 import android.view.SearchEvent; 52 import android.view.Surface; 53 import android.view.SurfaceControl; 54 import android.view.TextureView; 55 import android.view.View; 56 import android.view.ViewGroup; 57 import android.view.Window; 58 import android.view.WindowManager; 59 import android.view.WindowManager.LayoutParams; 60 import android.view.accessibility.AccessibilityEvent; 61 import android.view.animation.AccelerateDecelerateInterpolator; 62 import android.view.animation.DecelerateInterpolator; 63 import android.widget.ImageView; 64 import android.widget.TextView; 65 import android.widget.Toast; 66 67 import com.android.internal.policy.PhoneWindow; 68 import com.android.internal.policy.SystemBarUtils; 69 import com.android.nfc.R; 70 71 /** 72 * This class is responsible for handling the UI animation 73 * around Android Beam. The animation consists of the following 74 * animators: 75 * 76 * mPreAnimator: scales the screenshot down to INTERMEDIATE_SCALE 77 * mSlowSendAnimator: scales the screenshot down to 0.2f (used as a "send in progress" animation) 78 * mFastSendAnimator: quickly scales the screenshot down to 0.0f (used for send success) 79 * mFadeInAnimator: fades the current activity back in (used after mFastSendAnimator completes) 80 * mScaleUpAnimator: scales the screenshot back up to full screen (used for failure or receiving) 81 * mHintAnimator: Slowly turns up the alpha of the "Touch to Beam" hint 82 * 83 * Possible sequences are: 84 * 85 * mPreAnimator => mSlowSendAnimator => mFastSendAnimator => mFadeInAnimator (send success) 86 * mPreAnimator => mSlowSendAnimator => mScaleUpAnimator (send failure) 87 * mPreAnimator => mScaleUpAnimator (p2p link broken, or data received) 88 * 89 * Note that mFastSendAnimator and mFadeInAnimator are combined in a set, as they 90 * are an atomic animation that cannot be interrupted. 91 * 92 * All methods of this class must be called on the UI thread 93 */ 94 public class SendUi implements Animator.AnimatorListener, View.OnTouchListener, 95 TimeAnimator.TimeListener, TextureView.SurfaceTextureListener, android.view.Window.Callback { 96 static final String TAG = "SendUi"; 97 98 static final float INTERMEDIATE_SCALE = 0.6f; 99 100 static final float[] PRE_SCREENSHOT_SCALE = {1.0f, INTERMEDIATE_SCALE}; 101 static final int PRE_DURATION_MS = 350; 102 103 static final float[] SEND_SCREENSHOT_SCALE = {INTERMEDIATE_SCALE, 0.2f}; 104 static final int SLOW_SEND_DURATION_MS = 8000; // Stretch out sending over 8s 105 static final int FAST_SEND_DURATION_MS = 350; 106 107 static final float[] SCALE_UP_SCREENSHOT_SCALE = {INTERMEDIATE_SCALE, 1.0f}; 108 static final int SCALE_UP_DURATION_MS = 300; 109 110 static final int FADE_IN_DURATION_MS = 250; 111 static final int FADE_IN_START_DELAY_MS = 350; 112 113 static final int SLIDE_OUT_DURATION_MS = 300; 114 115 static final float[] BLACK_LAYER_ALPHA_DOWN_RANGE = {0.9f, 0.0f}; 116 static final float[] BLACK_LAYER_ALPHA_UP_RANGE = {0.0f, 0.9f}; 117 118 static final float[] TEXT_HINT_ALPHA_RANGE = {0.0f, 1.0f}; 119 static final int TEXT_HINT_ALPHA_DURATION_MS = 500; 120 static final int TEXT_HINT_ALPHA_START_DELAY_MS = 300; 121 122 public static final int FINISH_SCALE_UP = 0; 123 public static final int FINISH_SEND_SUCCESS = 1; 124 125 static final int STATE_IDLE = 0; 126 static final int STATE_W4_SCREENSHOT = 1; 127 static final int STATE_W4_SCREENSHOT_PRESEND_REQUESTED = 2; 128 static final int STATE_W4_SCREENSHOT_PRESEND_NFC_TAP_REQUESTED = 3; 129 static final int STATE_W4_SCREENSHOT_THEN_STOP = 4; 130 static final int STATE_W4_PRESEND = 5; 131 static final int STATE_W4_TOUCH = 6; 132 static final int STATE_W4_NFC_TAP = 7; 133 static final int STATE_SENDING = 8; 134 static final int STATE_COMPLETE = 9; 135 136 // all members are only used on UI thread 137 final WindowManager mWindowManager; 138 final Context mContext; 139 final Display mDisplay; 140 final DisplayMetrics mDisplayMetrics; 141 final Matrix mDisplayMatrix; 142 final WindowManager.LayoutParams mWindowLayoutParams; 143 final LayoutInflater mLayoutInflater; 144 final StatusBarManager mStatusBarManager; 145 final View mScreenshotLayout; 146 final ImageView mScreenshotView; 147 final ImageView mBlackLayer; 148 final TextureView mTextureView; 149 final TextView mTextHint; 150 final TextView mTextRetry; 151 final Callback mCallback; 152 153 // The mFrameCounter animation is purely used to count down a certain 154 // number of (vsync'd) frames. This is needed because the first 3 155 // times the animation internally calls eglSwapBuffers(), large buffers 156 // are allocated by the graphics drivers. This causes the animation 157 // to look janky. So on platforms where we can use hardware acceleration, 158 // the animation order is: 159 // Wait for hw surface => start frame counter => start pre-animation after 3 frames 160 // For platforms where no hw acceleration can be used, the pre-animation 161 // is started immediately. 162 final TimeAnimator mFrameCounterAnimator; 163 164 final ObjectAnimator mPreAnimator; 165 final ObjectAnimator mSlowSendAnimator; 166 final ObjectAnimator mFastSendAnimator; 167 final ObjectAnimator mFadeInAnimator; 168 final ObjectAnimator mHintAnimator; 169 final ObjectAnimator mScaleUpAnimator; 170 final ObjectAnimator mAlphaDownAnimator; 171 final ObjectAnimator mAlphaUpAnimator; 172 final AnimatorSet mSuccessAnimatorSet; 173 174 // Besides animating the screenshot, the Beam UI also renders 175 // fireflies on platforms where we can do hardware-acceleration. 176 // Firefly rendering is only started once the initial 177 // "pre-animation" has scaled down the screenshot, to avoid 178 // that animation becoming janky. Likewise, the fireflies are 179 // stopped in their tracks as soon as we finish the animation, 180 // to make the finishing animation smooth. 181 final boolean mHardwareAccelerated; 182 final FireflyRenderer mFireflyRenderer; 183 184 String mToastString; 185 Bitmap mScreenshotBitmap; 186 187 int mState; 188 int mRenderedFrames; 189 190 View mDecor; 191 192 // Used for holding the surface 193 SurfaceTexture mSurface; 194 int mSurfaceWidth; 195 int mSurfaceHeight; 196 197 public interface Callback { onSendConfirmed()198 public void onSendConfirmed(); onCanceled()199 public void onCanceled(); 200 } 201 SendUi(Context context, Callback callback)202 public SendUi(Context context, Callback callback) { 203 mContext = context; 204 mCallback = callback; 205 206 mDisplayMetrics = new DisplayMetrics(); 207 mDisplayMatrix = new Matrix(); 208 mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); 209 mStatusBarManager = (StatusBarManager) context.getSystemService(Context.STATUS_BAR_SERVICE); 210 211 mDisplay = mWindowManager.getDefaultDisplay(); 212 213 mLayoutInflater = (LayoutInflater) 214 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 215 mScreenshotLayout = mLayoutInflater.inflate(R.layout.screenshot, null); 216 217 mScreenshotView = (ImageView) mScreenshotLayout.findViewById(R.id.screenshot); 218 mScreenshotLayout.setFocusable(true); 219 220 mTextHint = (TextView) mScreenshotLayout.findViewById(R.id.calltoaction); 221 mTextRetry = (TextView) mScreenshotLayout.findViewById(R.id.retrytext); 222 mBlackLayer = (ImageView) mScreenshotLayout.findViewById(R.id.blacklayer); 223 mTextureView = (TextureView) mScreenshotLayout.findViewById(R.id.fireflies); 224 mTextureView.setSurfaceTextureListener(this); 225 226 // We're only allowed to use hardware acceleration if 227 // isHighEndGfx() returns true - otherwise, we're too limited 228 // on resources to do it. 229 mHardwareAccelerated = ActivityManager.isHighEndGfx(); 230 int hwAccelerationFlags = mHardwareAccelerated ? 231 WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED : 0; 232 233 mWindowLayoutParams = new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 234 ViewGroup.LayoutParams.MATCH_PARENT, 0, 0, 235 WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, 236 WindowManager.LayoutParams.FLAG_FULLSCREEN 237 | hwAccelerationFlags 238 | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN, 239 PixelFormat.OPAQUE); 240 mWindowLayoutParams.privateFlags |= 241 WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS; 242 mWindowLayoutParams.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS; 243 mWindowLayoutParams.token = new Binder(); 244 245 mFrameCounterAnimator = new TimeAnimator(); 246 mFrameCounterAnimator.setTimeListener(this); 247 248 PropertyValuesHolder preX = PropertyValuesHolder.ofFloat("scaleX", PRE_SCREENSHOT_SCALE); 249 PropertyValuesHolder preY = PropertyValuesHolder.ofFloat("scaleY", PRE_SCREENSHOT_SCALE); 250 mPreAnimator = ObjectAnimator.ofPropertyValuesHolder(mScreenshotView, preX, preY); 251 mPreAnimator.setInterpolator(new DecelerateInterpolator()); 252 mPreAnimator.setDuration(PRE_DURATION_MS); 253 mPreAnimator.addListener(this); 254 255 PropertyValuesHolder postX = PropertyValuesHolder.ofFloat("scaleX", SEND_SCREENSHOT_SCALE); 256 PropertyValuesHolder postY = PropertyValuesHolder.ofFloat("scaleY", SEND_SCREENSHOT_SCALE); 257 PropertyValuesHolder alphaDown = PropertyValuesHolder.ofFloat("alpha", 258 new float[]{1.0f, 0.0f}); 259 260 mSlowSendAnimator = ObjectAnimator.ofPropertyValuesHolder(mScreenshotView, postX, postY); 261 mSlowSendAnimator.setInterpolator(new DecelerateInterpolator()); 262 mSlowSendAnimator.setDuration(SLOW_SEND_DURATION_MS); 263 264 mFastSendAnimator = ObjectAnimator.ofPropertyValuesHolder(mScreenshotView, postX, 265 postY, alphaDown); 266 mFastSendAnimator.setInterpolator(new DecelerateInterpolator()); 267 mFastSendAnimator.setDuration(FAST_SEND_DURATION_MS); 268 mFastSendAnimator.addListener(this); 269 270 PropertyValuesHolder scaleUpX = PropertyValuesHolder.ofFloat("scaleX", SCALE_UP_SCREENSHOT_SCALE); 271 PropertyValuesHolder scaleUpY = PropertyValuesHolder.ofFloat("scaleY", SCALE_UP_SCREENSHOT_SCALE); 272 273 mScaleUpAnimator = ObjectAnimator.ofPropertyValuesHolder(mScreenshotView, scaleUpX, scaleUpY); 274 mScaleUpAnimator.setInterpolator(new DecelerateInterpolator()); 275 mScaleUpAnimator.setDuration(SCALE_UP_DURATION_MS); 276 mScaleUpAnimator.addListener(this); 277 278 PropertyValuesHolder fadeIn = PropertyValuesHolder.ofFloat("alpha", 1.0f); 279 mFadeInAnimator = ObjectAnimator.ofPropertyValuesHolder(mScreenshotView, fadeIn); 280 mFadeInAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); 281 mFadeInAnimator.setDuration(FADE_IN_DURATION_MS); 282 mFadeInAnimator.setStartDelay(FADE_IN_START_DELAY_MS); 283 mFadeInAnimator.addListener(this); 284 285 PropertyValuesHolder alphaUp = PropertyValuesHolder.ofFloat("alpha", TEXT_HINT_ALPHA_RANGE); 286 mHintAnimator = ObjectAnimator.ofPropertyValuesHolder(mTextHint, alphaUp); 287 mHintAnimator.setInterpolator(null); 288 mHintAnimator.setDuration(TEXT_HINT_ALPHA_DURATION_MS); 289 mHintAnimator.setStartDelay(TEXT_HINT_ALPHA_START_DELAY_MS); 290 291 alphaDown = PropertyValuesHolder.ofFloat("alpha", BLACK_LAYER_ALPHA_DOWN_RANGE); 292 mAlphaDownAnimator = ObjectAnimator.ofPropertyValuesHolder(mBlackLayer, alphaDown); 293 mAlphaDownAnimator.setInterpolator(new DecelerateInterpolator()); 294 mAlphaDownAnimator.setDuration(400); 295 296 alphaUp = PropertyValuesHolder.ofFloat("alpha", BLACK_LAYER_ALPHA_UP_RANGE); 297 mAlphaUpAnimator = ObjectAnimator.ofPropertyValuesHolder(mBlackLayer, alphaUp); 298 mAlphaUpAnimator.setInterpolator(new DecelerateInterpolator()); 299 mAlphaUpAnimator.setDuration(200); 300 301 mSuccessAnimatorSet = new AnimatorSet(); 302 mSuccessAnimatorSet.playSequentially(mFastSendAnimator, mFadeInAnimator); 303 304 // Create a Window with a Decor view; creating a window allows us to get callbacks 305 // on key events (which require a decor view to be dispatched). 306 mContext.setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen); 307 Window window = new PhoneWindow(mContext); 308 window.setCallback(this); 309 window.requestFeature(Window.FEATURE_NO_TITLE); 310 mDecor = window.getDecorView(); 311 window.setContentView(mScreenshotLayout, mWindowLayoutParams); 312 313 if (mHardwareAccelerated) { 314 mFireflyRenderer = new FireflyRenderer(context); 315 } else { 316 mFireflyRenderer = null; 317 } 318 mState = STATE_IDLE; 319 } 320 takeScreenshot()321 public void takeScreenshot() { 322 // There's no point in taking the screenshot if 323 // we're still finishing the previous animation. 324 if (mState >= STATE_W4_TOUCH) { 325 return; 326 } 327 mState = STATE_W4_SCREENSHOT; 328 new ScreenshotTask().execute(); 329 330 final IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 331 mContext.registerReceiver(mReceiver, filter, Context.RECEIVER_EXPORTED); 332 } 333 334 /** Show pre-send animation */ showPreSend(boolean promptToNfcTap)335 public void showPreSend(boolean promptToNfcTap) { 336 switch (mState) { 337 case STATE_IDLE: 338 Log.e(TAG, "Unexpected showPreSend() in STATE_IDLE"); 339 return; 340 case STATE_W4_SCREENSHOT: 341 // Still waiting for screenshot, store request in state 342 // and wait for screenshot completion. 343 if (promptToNfcTap) { 344 mState = STATE_W4_SCREENSHOT_PRESEND_NFC_TAP_REQUESTED; 345 } else { 346 mState = STATE_W4_SCREENSHOT_PRESEND_REQUESTED; 347 } 348 return; 349 case STATE_W4_SCREENSHOT_PRESEND_REQUESTED: 350 case STATE_W4_SCREENSHOT_PRESEND_NFC_TAP_REQUESTED: 351 Log.e(TAG, "Unexpected showPreSend() in STATE_W4_SCREENSHOT_PRESEND_REQUESTED"); 352 return; 353 case STATE_W4_PRESEND: 354 // Expected path, continue below 355 break; 356 default: 357 Log.e(TAG, "Unexpected showPreSend() in state " + Integer.toString(mState)); 358 return; 359 } 360 // Update display metrics 361 mDisplay.getRealMetrics(mDisplayMetrics); 362 363 final int statusBarHeight = SystemBarUtils.getStatusBarHeight(mContext); 364 365 mBlackLayer.setVisibility(View.GONE); 366 mBlackLayer.setAlpha(0f); 367 mScreenshotLayout.setOnTouchListener(this); 368 mScreenshotView.setImageBitmap(mScreenshotBitmap); 369 mScreenshotView.setTranslationX(0f); 370 mScreenshotView.setAlpha(1.0f); 371 mScreenshotView.setPadding(0, statusBarHeight, 0, 0); 372 373 mScreenshotLayout.requestFocus(); 374 375 if (promptToNfcTap) { 376 mTextHint.setText(mContext.getResources().getString(R.string.ask_nfc_tap)); 377 } else { 378 mTextHint.setText(mContext.getResources().getString(R.string.tap_to_beam)); 379 } 380 mTextHint.setAlpha(0.0f); 381 mTextHint.setVisibility(View.VISIBLE); 382 mHintAnimator.start(); 383 384 // Lock the orientation. 385 // The orientation from the configuration does not specify whether 386 // the orientation is reverse or not (ie landscape or reverse landscape). 387 // So we have to use SENSOR_LANDSCAPE or SENSOR_PORTRAIT to make sure 388 // we lock in portrait / landscape and have the sensor determine 389 // which way is up. 390 int orientation = mContext.getResources().getConfiguration().orientation; 391 392 switch (orientation) { 393 case Configuration.ORIENTATION_LANDSCAPE: 394 mWindowLayoutParams.screenOrientation = 395 ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE; 396 break; 397 case Configuration.ORIENTATION_PORTRAIT: 398 mWindowLayoutParams.screenOrientation = 399 ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT; 400 break; 401 default: 402 mWindowLayoutParams.screenOrientation = 403 ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT; 404 break; 405 } 406 407 mWindowManager.addView(mDecor, mWindowLayoutParams); 408 // Disable statusbar pull-down 409 mStatusBarManager.disable(StatusBarManager.DISABLE_EXPAND); 410 411 mToastString = null; 412 413 if (!mHardwareAccelerated) { 414 mPreAnimator.start(); 415 } // else, we will start the animation once we get the hardware surface 416 mState = promptToNfcTap ? STATE_W4_NFC_TAP : STATE_W4_TOUCH; 417 } 418 419 /** Show starting send animation */ showStartSend()420 public void showStartSend() { 421 if (mState < STATE_SENDING) return; 422 423 mTextRetry.setVisibility(View.GONE); 424 // Update the starting scale - touchscreen-mashers may trigger 425 // this before the pre-animation completes. 426 float currentScale = mScreenshotView.getScaleX(); 427 PropertyValuesHolder postX = PropertyValuesHolder.ofFloat("scaleX", 428 new float[] {currentScale, 0.0f}); 429 PropertyValuesHolder postY = PropertyValuesHolder.ofFloat("scaleY", 430 new float[] {currentScale, 0.0f}); 431 432 mSlowSendAnimator.setValues(postX, postY); 433 434 float currentAlpha = mBlackLayer.getAlpha(); 435 if (mBlackLayer.isShown() && currentAlpha > 0.0f) { 436 PropertyValuesHolder alphaDown = PropertyValuesHolder.ofFloat("alpha", 437 new float[] {currentAlpha, 0.0f}); 438 mAlphaDownAnimator.setValues(alphaDown); 439 mAlphaDownAnimator.start(); 440 } 441 mSlowSendAnimator.start(); 442 } 443 finishAndToast(int finishMode, String toast)444 public void finishAndToast(int finishMode, String toast) { 445 mToastString = toast; 446 447 finish(finishMode); 448 } 449 450 /** Return to initial state */ finish(int finishMode)451 public void finish(int finishMode) { 452 switch (mState) { 453 case STATE_IDLE: 454 return; 455 case STATE_W4_SCREENSHOT: 456 case STATE_W4_SCREENSHOT_PRESEND_REQUESTED: 457 case STATE_W4_SCREENSHOT_PRESEND_NFC_TAP_REQUESTED: 458 // Screenshot is still being captured on a separate thread. 459 // Update state, and stop everything when the capture is done. 460 mState = STATE_W4_SCREENSHOT_THEN_STOP; 461 return; 462 case STATE_W4_SCREENSHOT_THEN_STOP: 463 Log.e(TAG, "Unexpected call to finish() in STATE_W4_SCREENSHOT_THEN_STOP"); 464 return; 465 case STATE_W4_PRESEND: 466 // We didn't build up any animation state yet, but 467 // did store the bitmap. Clear out the bitmap, reset 468 // state and bail. 469 mScreenshotBitmap = null; 470 mState = STATE_IDLE; 471 return; 472 default: 473 // We've started animations and attached a view; tear stuff down below. 474 break; 475 } 476 477 // Stop rendering the fireflies 478 if (mFireflyRenderer != null) { 479 mFireflyRenderer.stop(); 480 } 481 482 mTextHint.setVisibility(View.GONE); 483 mTextRetry.setVisibility(View.GONE); 484 485 float currentScale = mScreenshotView.getScaleX(); 486 float currentAlpha = mScreenshotView.getAlpha(); 487 488 if (finishMode == FINISH_SCALE_UP) { 489 mBlackLayer.setVisibility(View.GONE); 490 PropertyValuesHolder scaleUpX = PropertyValuesHolder.ofFloat("scaleX", 491 new float[] {currentScale, 1.0f}); 492 PropertyValuesHolder scaleUpY = PropertyValuesHolder.ofFloat("scaleY", 493 new float[] {currentScale, 1.0f}); 494 PropertyValuesHolder scaleUpAlpha = PropertyValuesHolder.ofFloat("alpha", 495 new float[] {currentAlpha, 1.0f}); 496 mScaleUpAnimator.setValues(scaleUpX, scaleUpY, scaleUpAlpha); 497 498 mScaleUpAnimator.start(); 499 } else if (finishMode == FINISH_SEND_SUCCESS){ 500 // Modify the fast send parameters to match the current scale 501 PropertyValuesHolder postX = PropertyValuesHolder.ofFloat("scaleX", 502 new float[] {currentScale, 0.0f}); 503 PropertyValuesHolder postY = PropertyValuesHolder.ofFloat("scaleY", 504 new float[] {currentScale, 0.0f}); 505 PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 506 new float[] {currentAlpha, 0.0f}); 507 mFastSendAnimator.setValues(postX, postY, alpha); 508 509 // Reset the fadeIn parameters to start from alpha 1 510 PropertyValuesHolder fadeIn = PropertyValuesHolder.ofFloat("alpha", 511 new float[] {0.0f, 1.0f}); 512 mFadeInAnimator.setValues(fadeIn); 513 514 mSlowSendAnimator.cancel(); 515 mSuccessAnimatorSet.start(); 516 } 517 mState = STATE_COMPLETE; 518 } 519 dismiss()520 void dismiss() { 521 if (mState < STATE_W4_TOUCH) return; 522 // Immediately set to IDLE, to prevent .cancel() calls 523 // below from immediately calling into dismiss() again. 524 // (They can do so on the same thread). 525 mState = STATE_IDLE; 526 mSurface = null; 527 mFrameCounterAnimator.cancel(); 528 mPreAnimator.cancel(); 529 mSlowSendAnimator.cancel(); 530 mFastSendAnimator.cancel(); 531 mSuccessAnimatorSet.cancel(); 532 mScaleUpAnimator.cancel(); 533 mAlphaUpAnimator.cancel(); 534 mAlphaDownAnimator.cancel(); 535 mWindowManager.removeView(mDecor); 536 mStatusBarManager.disable(StatusBarManager.DISABLE_NONE); 537 mScreenshotBitmap = null; 538 mContext.unregisterReceiver(mReceiver); 539 if (mToastString != null) { 540 Toast toast = Toast.makeText(mContext, mToastString, Toast.LENGTH_LONG); 541 toast.getWindowParams().privateFlags |= LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS; 542 toast.show(); 543 } 544 mToastString = null; 545 } 546 547 /** 548 * @return the current display rotation in degrees 549 */ getDegreesForRotation(int value)550 static float getDegreesForRotation(int value) { 551 switch (value) { 552 case Surface.ROTATION_90: 553 return 90f; 554 case Surface.ROTATION_180: 555 return 180f; 556 case Surface.ROTATION_270: 557 return 270f; 558 } 559 return 0f; 560 } 561 562 final class ScreenshotTask extends AsyncTask<Void, Void, Bitmap> { 563 @Override doInBackground(Void... params)564 protected Bitmap doInBackground(Void... params) { 565 return createScreenshot(); 566 } 567 568 @Override onPostExecute(Bitmap result)569 protected void onPostExecute(Bitmap result) { 570 if (mState == STATE_W4_SCREENSHOT) { 571 // Screenshot done, wait for request to start preSend anim 572 mScreenshotBitmap = result; 573 mState = STATE_W4_PRESEND; 574 } else if (mState == STATE_W4_SCREENSHOT_THEN_STOP) { 575 // We were asked to finish, move to idle state and exit 576 mState = STATE_IDLE; 577 } else if (mState == STATE_W4_SCREENSHOT_PRESEND_REQUESTED || 578 mState == STATE_W4_SCREENSHOT_PRESEND_NFC_TAP_REQUESTED) { 579 mScreenshotBitmap = result; 580 boolean requestTap = (mState == STATE_W4_SCREENSHOT_PRESEND_NFC_TAP_REQUESTED); 581 mState = STATE_W4_PRESEND; 582 showPreSend(requestTap); 583 } else { 584 Log.e(TAG, "Invalid state on screenshot completion: " + Integer.toString(mState)); 585 } 586 } 587 }; 588 589 /** 590 * Returns a screenshot of the current display contents. 591 */ createScreenshot()592 Bitmap createScreenshot() { 593 boolean hasNavBar = mContext.getResources().getBoolean( 594 com.android.internal.R.bool.config_showNavigationBar); 595 final int statusBarHeight = SystemBarUtils.getStatusBarHeight(mContext); 596 597 // Navbar has different sizes, depending on orientation 598 final int navBarHeight = hasNavBar ? mContext.getResources().getDimensionPixelSize( 599 com.android.internal.R.dimen.navigation_bar_height) : 0; 600 final int navBarHeightLandscape = hasNavBar ? mContext.getResources().getDimensionPixelSize( 601 com.android.internal.R.dimen.navigation_bar_height_landscape) : 0; 602 603 final int navBarWidth = hasNavBar ? mContext.getResources().getDimensionPixelSize( 604 com.android.internal.R.dimen.navigation_bar_width) : 0; 605 606 mDisplay.getRealMetrics(mDisplayMetrics); 607 float smallestWidth = (float)Math.min(mDisplayMetrics.widthPixels, 608 mDisplayMetrics.heightPixels); 609 float smallestWidthDp = smallestWidth / (mDisplayMetrics.densityDpi / 160f); 610 611 // TODO this is somewhat device-specific; need generic solution. 612 // The starting crop for the screenshot is the fullscreen without the status bar, which 613 // is always on top. The conditional check will determine how to crop the navbar, 614 // depending on orienation and screen size. 615 Rect crop = new Rect(0, statusBarHeight, mDisplayMetrics.widthPixels, 616 mDisplayMetrics.heightPixels); 617 if (mDisplayMetrics.widthPixels < mDisplayMetrics.heightPixels) { 618 // Portrait mode: crop the navbar out from the bottom, width unchanged 619 crop.bottom -= navBarHeight; 620 } else { 621 // Landscape mode: 622 if (smallestWidthDp > 599) { 623 // Navbar on bottom on >599dp width devices, so crop navbar out from the bottom. 624 crop.bottom -= navBarHeightLandscape; 625 } else { 626 // Navbar on right, so crop navbar out from right of screen. 627 crop.right -= navBarWidth; 628 } 629 } 630 631 int width = crop.width(); 632 int height = crop.height(); 633 // Take the screenshot. SurfaceControl will generate a hardware bitmap in the correct 634 // orientation and size. 635 IBinder displayToken = SurfaceControl.getInternalDisplayToken(); 636 final SurfaceControl.DisplayCaptureArgs captureArgs = 637 new SurfaceControl.DisplayCaptureArgs.Builder(displayToken) 638 .setSourceCrop(crop) 639 .setSize(width, height) 640 .build(); 641 SurfaceControl.ScreenshotHardwareBuffer screenshotBuffer = 642 SurfaceControl.captureDisplay(captureArgs); 643 final Bitmap bitmap = screenshotBuffer == null ? null : screenshotBuffer.asBitmap(); 644 645 // Bail if we couldn't take the screenshot 646 if (bitmap == null) { 647 return null; 648 } 649 650 // Convert to a software bitmap so it can be set in an ImageView. 651 Bitmap swBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true); 652 return swBitmap; 653 } 654 655 @Override onAnimationStart(Animator animation)656 public void onAnimationStart(Animator animation) { } 657 658 @Override onAnimationEnd(Animator animation)659 public void onAnimationEnd(Animator animation) { 660 if (animation == mScaleUpAnimator || animation == mSuccessAnimatorSet || 661 animation == mFadeInAnimator) { 662 // These all indicate the end of the animation 663 dismiss(); 664 } else if (animation == mFastSendAnimator) { 665 // After sending is done and we've faded out, reset the scale to 1 666 // so we can fade it back in. 667 mScreenshotView.setScaleX(1.0f); 668 mScreenshotView.setScaleY(1.0f); 669 } else if (animation == mPreAnimator) { 670 if (mHardwareAccelerated && (mState == STATE_W4_TOUCH || mState == STATE_W4_NFC_TAP)) { 671 mFireflyRenderer.start(mSurface, mSurfaceWidth, mSurfaceHeight); 672 } 673 } 674 } 675 676 @Override onAnimationCancel(Animator animation)677 public void onAnimationCancel(Animator animation) { } 678 679 @Override onAnimationRepeat(Animator animation)680 public void onAnimationRepeat(Animator animation) { } 681 682 @Override onTimeUpdate(TimeAnimator animation, long totalTime, long deltaTime)683 public void onTimeUpdate(TimeAnimator animation, long totalTime, long deltaTime) { 684 // This gets called on animation vsync 685 if (++mRenderedFrames < 4) { 686 // For the first 3 frames, call invalidate(); this calls eglSwapBuffers 687 // on the surface, which will allocate large buffers the first three calls 688 // as Android uses triple buffering. 689 mScreenshotLayout.invalidate(); 690 } else { 691 // Buffers should be allocated, start the real animation 692 mFrameCounterAnimator.cancel(); 693 mPreAnimator.start(); 694 } 695 } 696 697 @Override onTouch(View v, MotionEvent event)698 public boolean onTouch(View v, MotionEvent event) { 699 if (mState != STATE_W4_TOUCH) { 700 return false; 701 } 702 mState = STATE_SENDING; 703 // Ignore future touches 704 mScreenshotView.setOnTouchListener(null); 705 706 // Cancel any ongoing animations 707 mFrameCounterAnimator.cancel(); 708 mPreAnimator.cancel(); 709 710 mCallback.onSendConfirmed(); 711 return true; 712 } 713 714 @Override onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height)715 public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { 716 if (mHardwareAccelerated && mState < STATE_COMPLETE) { 717 mRenderedFrames = 0; 718 719 mFrameCounterAnimator.start(); 720 mSurface = surface; 721 mSurfaceWidth = width; 722 mSurfaceHeight = height; 723 } 724 } 725 726 @Override onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height)727 public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { 728 // Since we've disabled orientation changes, we can safely ignore this 729 } 730 731 @Override onSurfaceTextureDestroyed(SurfaceTexture surface)732 public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { 733 mSurface = null; 734 735 return true; 736 } 737 738 @Override onSurfaceTextureUpdated(SurfaceTexture surface)739 public void onSurfaceTextureUpdated(SurfaceTexture surface) { } 740 showSendHint()741 public void showSendHint() { 742 if (mAlphaDownAnimator.isRunning()) { 743 mAlphaDownAnimator.cancel(); 744 } 745 if (mSlowSendAnimator.isRunning()) { 746 mSlowSendAnimator.cancel(); 747 } 748 mBlackLayer.setScaleX(mScreenshotView.getScaleX()); 749 mBlackLayer.setScaleY(mScreenshotView.getScaleY()); 750 mBlackLayer.setVisibility(View.VISIBLE); 751 mTextHint.setVisibility(View.GONE); 752 753 mTextRetry.setText(mContext.getResources().getString(R.string.beam_try_again)); 754 mTextRetry.setVisibility(View.VISIBLE); 755 756 PropertyValuesHolder alphaUp = PropertyValuesHolder.ofFloat("alpha", 757 new float[] {mBlackLayer.getAlpha(), 0.9f}); 758 mAlphaUpAnimator.setValues(alphaUp); 759 mAlphaUpAnimator.start(); 760 } 761 762 @Override dispatchKeyEvent(KeyEvent event)763 public boolean dispatchKeyEvent(KeyEvent event) { 764 int keyCode = event.getKeyCode(); 765 if (keyCode == KeyEvent.KEYCODE_BACK) { 766 mCallback.onCanceled(); 767 return true; 768 } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || 769 keyCode == KeyEvent.KEYCODE_VOLUME_UP) { 770 // Treat as if it's a touch event 771 return onTouch(mScreenshotView, null); 772 } else { 773 return false; 774 } 775 } 776 777 @Override dispatchKeyShortcutEvent(KeyEvent event)778 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 779 return false; 780 } 781 782 @Override dispatchTouchEvent(MotionEvent event)783 public boolean dispatchTouchEvent(MotionEvent event) { 784 return mScreenshotLayout.dispatchTouchEvent(event); 785 } 786 787 @Override dispatchTrackballEvent(MotionEvent event)788 public boolean dispatchTrackballEvent(MotionEvent event) { 789 return false; 790 } 791 792 @Override dispatchGenericMotionEvent(MotionEvent event)793 public boolean dispatchGenericMotionEvent(MotionEvent event) { 794 return false; 795 } 796 797 @Override dispatchPopulateAccessibilityEvent(AccessibilityEvent event)798 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 799 return false; 800 } 801 802 @Override onCreatePanelView(int featureId)803 public View onCreatePanelView(int featureId) { 804 return null; 805 } 806 807 @Override onCreatePanelMenu(int featureId, Menu menu)808 public boolean onCreatePanelMenu(int featureId, Menu menu) { 809 return false; 810 } 811 812 @Override onPreparePanel(int featureId, View view, Menu menu)813 public boolean onPreparePanel(int featureId, View view, Menu menu) { 814 return false; 815 } 816 817 @Override onMenuOpened(int featureId, Menu menu)818 public boolean onMenuOpened(int featureId, Menu menu) { 819 return false; 820 } 821 822 @Override onMenuItemSelected(int featureId, MenuItem item)823 public boolean onMenuItemSelected(int featureId, MenuItem item) { 824 return false; 825 } 826 827 @Override onWindowAttributesChanged(LayoutParams attrs)828 public void onWindowAttributesChanged(LayoutParams attrs) { 829 } 830 831 @Override onContentChanged()832 public void onContentChanged() { 833 } 834 835 @Override onWindowFocusChanged(boolean hasFocus)836 public void onWindowFocusChanged(boolean hasFocus) { 837 } 838 839 @Override onAttachedToWindow()840 public void onAttachedToWindow() { 841 842 } 843 844 @Override onDetachedFromWindow()845 public void onDetachedFromWindow() { 846 } 847 848 @Override onPanelClosed(int featureId, Menu menu)849 public void onPanelClosed(int featureId, Menu menu) { 850 851 } 852 853 @Override onSearchRequested(SearchEvent searchEvent)854 public boolean onSearchRequested(SearchEvent searchEvent) { 855 return onSearchRequested(); 856 } 857 858 @Override onSearchRequested()859 public boolean onSearchRequested() { 860 return false; 861 } 862 863 @Override onWindowStartingActionMode( android.view.ActionMode.Callback callback)864 public ActionMode onWindowStartingActionMode( 865 android.view.ActionMode.Callback callback) { 866 return null; 867 } 868 onWindowStartingActionMode( android.view.ActionMode.Callback callback, int type)869 public ActionMode onWindowStartingActionMode( 870 android.view.ActionMode.Callback callback, int type) { 871 return null; 872 } 873 874 @Override onActionModeStarted(ActionMode mode)875 public void onActionModeStarted(ActionMode mode) { 876 } 877 878 @Override onActionModeFinished(ActionMode mode)879 public void onActionModeFinished(ActionMode mode) { 880 } 881 isSendUiInIdleState()882 public boolean isSendUiInIdleState() { 883 return mState == STATE_IDLE; 884 } 885 886 private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 887 @Override 888 public void onReceive(Context context, Intent intent) { 889 if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.getAction())) { 890 mCallback.onCanceled(); 891 } 892 } 893 }; 894 } 895