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