GlobalScreenshot.java revision d859fa399133da32705415e138c897f263ae99ad
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 17package com.android.systemui.screenshot; 18 19import android.animation.Animator; 20import android.animation.AnimatorListenerAdapter; 21import android.animation.AnimatorSet; 22import android.animation.ObjectAnimator; 23import android.animation.TimeInterpolator; 24import android.animation.ValueAnimator; 25import android.animation.ValueAnimator.AnimatorUpdateListener; 26import android.app.Activity; 27import android.content.ContentValues; 28import android.content.Context; 29import android.graphics.Bitmap; 30import android.graphics.Canvas; 31import android.graphics.Matrix; 32import android.graphics.PixelFormat; 33import android.media.MediaScannerConnection; 34import android.net.Uri; 35import android.os.AsyncTask; 36import android.os.Binder; 37import android.os.Environment; 38import android.os.ServiceManager; 39import android.provider.MediaStore; 40import android.util.DisplayMetrics; 41import android.util.Log; 42import android.view.Display; 43import android.view.IWindowManager; 44import android.view.LayoutInflater; 45import android.view.MotionEvent; 46import android.view.Surface; 47import android.view.View; 48import android.view.ViewGroup; 49import android.view.WindowManager; 50import android.widget.FrameLayout; 51import android.widget.ImageView; 52import android.widget.TextView; 53import android.widget.Toast; 54 55import com.android.systemui.R; 56 57import java.io.File; 58import java.io.FileOutputStream; 59import java.io.IOException; 60import java.io.OutputStream; 61import java.lang.Thread; 62import java.text.SimpleDateFormat; 63import java.util.Date; 64 65/** 66 * POD used in the AsyncTask which saves an image in the background. 67 */ 68class SaveImageInBackgroundData { 69 Context context; 70 Bitmap image; 71 int result; 72} 73 74/** 75 * An AsyncTask that saves an image to the media store in the background. 76 */ 77class SaveImageInBackgroundTask extends AsyncTask<SaveImageInBackgroundData, Void, 78 SaveImageInBackgroundData> { 79 private static final String TAG = "SaveImageInBackgroundTask"; 80 private static final String SCREENSHOTS_DIR_NAME = "Screenshots"; 81 private static final String SCREENSHOT_FILE_PATH_TEMPLATE = "%s/%s/Screenshot_%s-%d.png"; 82 83 @Override 84 protected SaveImageInBackgroundData doInBackground(SaveImageInBackgroundData... params) { 85 if (params.length != 1) return null; 86 87 Context context = params[0].context; 88 Bitmap image = params[0].image; 89 90 try { 91 long currentTime = System.currentTimeMillis(); 92 String date = new SimpleDateFormat("MM-dd-yy-kk-mm-ss").format(new Date(currentTime)); 93 String imageDir = Environment.getExternalStoragePublicDirectory( 94 Environment.DIRECTORY_PICTURES).getAbsolutePath(); 95 String imageFilePath = String.format(SCREENSHOT_FILE_PATH_TEMPLATE, 96 imageDir, SCREENSHOTS_DIR_NAME, 97 date, currentTime % 1000); 98 99 // Save the screenshot to the MediaStore 100 ContentValues values = new ContentValues(); 101 values.put(MediaStore.Images.ImageColumns.DATA, imageFilePath); 102 values.put(MediaStore.Images.ImageColumns.TITLE, "Screenshot"); 103 values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, "Screenshot"); 104 values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, currentTime); 105 values.put(MediaStore.Images.ImageColumns.DATE_ADDED, currentTime); 106 values.put(MediaStore.Images.ImageColumns.DATE_MODIFIED, currentTime); 107 values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/png"); 108 Uri uri = context.getContentResolver().insert( 109 MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); 110 111 OutputStream out = context.getContentResolver().openOutputStream(uri); 112 image.compress(Bitmap.CompressFormat.PNG, 100, out); 113 out.flush(); 114 out.close(); 115 116 params[0].result = 0; 117 } catch (Exception e) { 118 // IOException/UnsupportedOperationException may be thrown if external storage is not 119 // mounted 120 params[0].result = 1; 121 } 122 123 return params[0]; 124 }; 125 126 @Override 127 protected void onPostExecute(SaveImageInBackgroundData params) { 128 if (params.result > 0) { 129 // Show a message that we've failed to save the image to disk 130 Toast.makeText(params.context, R.string.screenshot_failed_toast, 131 Toast.LENGTH_SHORT).show(); 132 } else { 133 // Show a message that we've saved the screenshot to disk 134 Toast.makeText(params.context, R.string.screenshot_saving_toast, 135 Toast.LENGTH_SHORT).show(); 136 } 137 }; 138} 139 140/** 141 * TODO: 142 * - Performance when over gl surfaces? Ie. Gallery 143 * - what do we say in the Toast? Which icon do we get if the user uses another 144 * type of gallery? 145 */ 146class GlobalScreenshot { 147 private static final String TAG = "GlobalScreenshot"; 148 private static final int SCREENSHOT_FADE_IN_DURATION = 900; 149 private static final int SCREENSHOT_FADE_OUT_DELAY = 1000; 150 private static final int SCREENSHOT_FADE_OUT_DURATION = 450; 151 private static final int TOAST_FADE_IN_DURATION = 500; 152 private static final int TOAST_FADE_OUT_DELAY = 1000; 153 private static final int TOAST_FADE_OUT_DURATION = 500; 154 private static final float BACKGROUND_ALPHA = 0.65f; 155 private static final float SCREENSHOT_SCALE = 0.85f; 156 private static final float SCREENSHOT_MIN_SCALE = 0.7f; 157 private static final float SCREENSHOT_ROTATION = -6.75f; // -12.5f; 158 159 private Context mContext; 160 private LayoutInflater mLayoutInflater; 161 private IWindowManager mIWindowManager; 162 private WindowManager mWindowManager; 163 private WindowManager.LayoutParams mWindowLayoutParams; 164 private Display mDisplay; 165 private DisplayMetrics mDisplayMetrics; 166 private Matrix mDisplayMatrix; 167 168 private Bitmap mScreenBitmap; 169 private View mScreenshotLayout; 170 private ImageView mBackgroundView; 171 private FrameLayout mScreenshotContainerView; 172 private ImageView mScreenshotView; 173 174 private AnimatorSet mScreenshotAnimation; 175 176 // General use cubic interpolator 177 final TimeInterpolator mCubicInterpolator = new TimeInterpolator() { 178 public float getInterpolation(float t) { 179 return t*t*t; 180 } 181 }; 182 // The interpolator used to control the background alpha at the start of the animation 183 final TimeInterpolator mBackgroundViewAlphaInterpolator = new TimeInterpolator() { 184 public float getInterpolation(float t) { 185 float tStep = 0.35f; 186 if (t < tStep) { 187 return t * (1f / tStep); 188 } else { 189 return 1f; 190 } 191 } 192 }; 193 194 /** 195 * @param context everything needs a context :( 196 */ 197 public GlobalScreenshot(Context context) { 198 mContext = context; 199 mLayoutInflater = (LayoutInflater) 200 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 201 202 // Inflate the screenshot layout 203 mDisplayMetrics = new DisplayMetrics(); 204 mDisplayMatrix = new Matrix(); 205 mScreenshotLayout = mLayoutInflater.inflate(R.layout.global_screenshot, null); 206 mBackgroundView = (ImageView) mScreenshotLayout.findViewById(R.id.global_screenshot_background); 207 mScreenshotContainerView = (FrameLayout) mScreenshotLayout.findViewById(R.id.global_screenshot_container); 208 mScreenshotView = (ImageView) mScreenshotLayout.findViewById(R.id.global_screenshot); 209 mScreenshotLayout.setFocusable(true); 210 mScreenshotLayout.setOnTouchListener(new View.OnTouchListener() { 211 @Override 212 public boolean onTouch(View v, MotionEvent event) { 213 // Intercept and ignore all touch events 214 return true; 215 } 216 }); 217 218 // Setup the window that we are going to use 219 mIWindowManager = IWindowManager.Stub.asInterface( 220 ServiceManager.getService(Context.WINDOW_SERVICE)); 221 mWindowLayoutParams = new WindowManager.LayoutParams( 222 ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 0, 0, 223 WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY, 224 WindowManager.LayoutParams.FLAG_FULLSCREEN 225 | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED 226 | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED_SYSTEM 227 | WindowManager.LayoutParams.FLAG_KEEP_SURFACE_WHILE_ANIMATING 228 | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN 229 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED, 230 PixelFormat.TRANSLUCENT); 231 mWindowLayoutParams.token = new Binder(); 232 mWindowLayoutParams.setTitle("ScreenshotAnimation"); 233 mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); 234 mDisplay = mWindowManager.getDefaultDisplay(); 235 } 236 237 /** 238 * Creates a new worker thread and saves the screenshot to the media store. 239 */ 240 private void saveScreenshotInWorkerThread() { 241 SaveImageInBackgroundData data = new SaveImageInBackgroundData(); 242 data.context = mContext; 243 data.image = mScreenBitmap; 244 new SaveImageInBackgroundTask().execute(data); 245 } 246 247 /** 248 * @return the current display rotation in degrees 249 */ 250 private float getDegreesForRotation(int value) { 251 switch (value) { 252 case Surface.ROTATION_90: 253 return 90f; 254 case Surface.ROTATION_180: 255 return 180f; 256 case Surface.ROTATION_270: 257 return 270f; 258 } 259 return 0f; 260 } 261 262 /** 263 * Takes a screenshot of the current display and shows an animation. 264 */ 265 void takeScreenshot() { 266 // We need to orient the screenshot correctly (and the Surface api seems to take screenshots 267 // only in the natural orientation of the device :!) 268 mDisplay.getRealMetrics(mDisplayMetrics); 269 float[] dims = {mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels}; 270 float degrees = getDegreesForRotation(mDisplay.getRotation()); 271 boolean requiresRotation = (degrees > 0); 272 if (requiresRotation) { 273 // Get the dimensions of the device in its native orientation 274 mDisplayMatrix.reset(); 275 mDisplayMatrix.preRotate(-degrees); 276 mDisplayMatrix.mapPoints(dims); 277 dims[0] = Math.abs(dims[0]); 278 dims[1] = Math.abs(dims[1]); 279 } 280 mScreenBitmap = Surface.screenshot((int) dims[0], (int) dims[1]); 281 if (requiresRotation) { 282 // Rotate the screenshot to the current orientation 283 Bitmap ss = Bitmap.createBitmap(mDisplayMetrics.widthPixels, 284 mDisplayMetrics.heightPixels, Bitmap.Config.ARGB_8888); 285 Canvas c = new Canvas(ss); 286 c.translate(ss.getWidth() / 2, ss.getHeight() / 2); 287 c.rotate(360f - degrees); 288 c.translate(-dims[0] / 2, -dims[1] / 2); 289 c.drawBitmap(mScreenBitmap, 0, 0, null); 290 mScreenBitmap = ss; 291 } 292 293 // If we couldn't take the screenshot, notify the user 294 if (mScreenBitmap == null) { 295 Toast.makeText(mContext, R.string.screenshot_failed_toast, 296 Toast.LENGTH_SHORT).show(); 297 return; 298 } 299 300 // Start the post-screenshot animation 301 startAnimation(); 302 } 303 304 305 /** 306 * Starts the animation after taking the screenshot 307 */ 308 private void startAnimation() { 309 // Add the view for the animation 310 mScreenshotView.setImageBitmap(mScreenBitmap); 311 mScreenshotLayout.requestFocus(); 312 313 // Setup the animation with the screenshot just taken 314 if (mScreenshotAnimation != null) { 315 mScreenshotAnimation.end(); 316 } 317 318 mWindowManager.addView(mScreenshotLayout, mWindowLayoutParams); 319 ValueAnimator screenshotFadeInAnim = createScreenshotFadeInAnimation(); 320 ValueAnimator screenshotFadeOutAnim = createScreenshotFadeOutAnimation(); 321 mScreenshotAnimation = new AnimatorSet(); 322 mScreenshotAnimation.play(screenshotFadeInAnim).before(screenshotFadeOutAnim); 323 mScreenshotAnimation.addListener(new AnimatorListenerAdapter() { 324 @Override 325 public void onAnimationEnd(Animator animation) { 326 // Save the screenshot once we have a bit of time now 327 saveScreenshotInWorkerThread(); 328 329 mWindowManager.removeView(mScreenshotLayout); 330 } 331 }); 332 mScreenshotAnimation.start(); 333 } 334 private ValueAnimator createScreenshotFadeInAnimation() { 335 ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f); 336 anim.setInterpolator(mCubicInterpolator); 337 anim.setDuration(SCREENSHOT_FADE_IN_DURATION); 338 anim.addListener(new AnimatorListenerAdapter() { 339 @Override 340 public void onAnimationStart(Animator animation) { 341 mBackgroundView.setVisibility(View.VISIBLE); 342 mScreenshotContainerView.setVisibility(View.VISIBLE); 343 } 344 }); 345 anim.addUpdateListener(new AnimatorUpdateListener() { 346 @Override 347 public void onAnimationUpdate(ValueAnimator animation) { 348 float t = ((Float) animation.getAnimatedValue()).floatValue(); 349 mBackgroundView.setAlpha(mBackgroundViewAlphaInterpolator.getInterpolation(t) * 350 BACKGROUND_ALPHA); 351 float scaleT = SCREENSHOT_SCALE + (1f - t) * SCREENSHOT_SCALE; 352 mScreenshotContainerView.setAlpha(t*t*t*t); 353 mScreenshotContainerView.setScaleX(scaleT); 354 mScreenshotContainerView.setScaleY(scaleT); 355 mScreenshotContainerView.setRotation(t * SCREENSHOT_ROTATION); 356 } 357 }); 358 return anim; 359 } 360 private ValueAnimator createScreenshotFadeOutAnimation() { 361 ValueAnimator anim = ValueAnimator.ofFloat(1f, 0f); 362 anim.setInterpolator(mCubicInterpolator); 363 anim.setStartDelay(SCREENSHOT_FADE_OUT_DELAY); 364 anim.setDuration(SCREENSHOT_FADE_OUT_DURATION); 365 anim.addListener(new AnimatorListenerAdapter() { 366 @Override 367 public void onAnimationEnd(Animator animation) { 368 mBackgroundView.setVisibility(View.GONE); 369 mScreenshotContainerView.setVisibility(View.GONE); 370 } 371 }); 372 anim.addUpdateListener(new AnimatorUpdateListener() { 373 @Override 374 public void onAnimationUpdate(ValueAnimator animation) { 375 float t = ((Float) animation.getAnimatedValue()).floatValue(); 376 float scaleT = SCREENSHOT_MIN_SCALE + 377 t*(SCREENSHOT_SCALE - SCREENSHOT_MIN_SCALE); 378 mScreenshotContainerView.setAlpha(t); 379 mScreenshotContainerView.setScaleX(scaleT); 380 mScreenshotContainerView.setScaleY(scaleT); 381 mBackgroundView.setAlpha(t * t * BACKGROUND_ALPHA); 382 } 383 }); 384 return anim; 385 } 386} 387