GlobalScreenshot.java revision 9112ec3039dda4186c6f957981237c0691db2269
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(IOException e){
118            params[0].result = 1;
119        }
120
121        return params[0];
122    };
123
124    @Override
125    protected void onPostExecute(SaveImageInBackgroundData params) {
126        if (params.result > 0) {
127            // Show a message that we've failed to save the image to disk
128            Toast.makeText(params.context, R.string.screenshot_failed_toast,
129                    Toast.LENGTH_SHORT).show();
130        } else {
131            // Show a message that we've saved the screenshot to disk
132            Toast.makeText(params.context, R.string.screenshot_saving_toast,
133                    Toast.LENGTH_SHORT).show();
134        }
135    };
136}
137
138/**
139 * TODO:
140 *   - Performance when over gl surfaces? Ie. Gallery
141 *   - what do we say in the Toast? Which icon do we get if the user uses another
142 *     type of gallery?
143 */
144class GlobalScreenshot {
145    private static final String TAG = "GlobalScreenshot";
146    private static final int SCREENSHOT_FADE_IN_DURATION = 900;
147    private static final int SCREENSHOT_FADE_OUT_DELAY = 1000;
148    private static final int SCREENSHOT_FADE_OUT_DURATION = 450;
149    private static final int TOAST_FADE_IN_DURATION = 500;
150    private static final int TOAST_FADE_OUT_DELAY = 1000;
151    private static final int TOAST_FADE_OUT_DURATION = 500;
152    private static final float BACKGROUND_ALPHA = 0.65f;
153    private static final float SCREENSHOT_SCALE = 0.85f;
154    private static final float SCREENSHOT_MIN_SCALE = 0.7f;
155    private static final float SCREENSHOT_ROTATION = -6.75f; // -12.5f;
156
157    private Context mContext;
158    private LayoutInflater mLayoutInflater;
159    private IWindowManager mIWindowManager;
160    private WindowManager mWindowManager;
161    private WindowManager.LayoutParams mWindowLayoutParams;
162    private Display mDisplay;
163    private DisplayMetrics mDisplayMetrics;
164    private Matrix mDisplayMatrix;
165
166    private Bitmap mScreenBitmap;
167    private View mScreenshotLayout;
168    private ImageView mBackgroundView;
169    private FrameLayout mScreenshotContainerView;
170    private ImageView mScreenshotView;
171
172    private AnimatorSet mScreenshotAnimation;
173
174    // General use cubic interpolator
175    final TimeInterpolator mCubicInterpolator = new TimeInterpolator() {
176        public float getInterpolation(float t) {
177            return t*t*t;
178        }
179    };
180    // The interpolator used to control the background alpha at the start of the animation
181    final TimeInterpolator mBackgroundViewAlphaInterpolator = new TimeInterpolator() {
182        public float getInterpolation(float t) {
183            float tStep = 0.35f;
184            if (t < tStep) {
185                return t * (1f / tStep);
186            } else {
187                return 1f;
188            }
189        }
190    };
191
192    /**
193     * @param context everything needs a context :(
194     */
195    public GlobalScreenshot(Context context) {
196        mContext = context;
197        mLayoutInflater = (LayoutInflater)
198                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
199
200        // Inflate the screenshot layout
201        mDisplayMetrics = new DisplayMetrics();
202        mDisplayMatrix = new Matrix();
203        mScreenshotLayout = mLayoutInflater.inflate(R.layout.global_screenshot, null);
204        mBackgroundView = (ImageView) mScreenshotLayout.findViewById(R.id.global_screenshot_background);
205        mScreenshotContainerView = (FrameLayout) mScreenshotLayout.findViewById(R.id.global_screenshot_container);
206        mScreenshotView = (ImageView) mScreenshotLayout.findViewById(R.id.global_screenshot);
207        mScreenshotLayout.setFocusable(true);
208        mScreenshotLayout.setOnTouchListener(new View.OnTouchListener() {
209            @Override
210            public boolean onTouch(View v, MotionEvent event) {
211                // Intercept and ignore all touch events
212                return true;
213            }
214        });
215
216        // Setup the window that we are going to use
217        mIWindowManager = IWindowManager.Stub.asInterface(
218                ServiceManager.getService(Context.WINDOW_SERVICE));
219        mWindowLayoutParams = new WindowManager.LayoutParams(
220                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 0, 0,
221                WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY,
222                WindowManager.LayoutParams.FLAG_FULLSCREEN
223                    | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
224                    | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED_SYSTEM
225                    | WindowManager.LayoutParams.FLAG_KEEP_SURFACE_WHILE_ANIMATING
226                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
227                    | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED,
228                PixelFormat.TRANSLUCENT);
229        mWindowLayoutParams.token = new Binder();
230        mWindowLayoutParams.setTitle("ScreenshotAnimation");
231        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
232        mDisplay = mWindowManager.getDefaultDisplay();
233    }
234
235    /**
236     * Creates a new worker thread and saves the screenshot to the media store.
237     */
238    private void saveScreenshotInWorkerThread() {
239        SaveImageInBackgroundData data = new SaveImageInBackgroundData();
240        data.context = mContext;
241        data.image = mScreenBitmap;
242        new SaveImageInBackgroundTask().execute(data);
243    }
244
245    /**
246     * @return the current display rotation in degrees
247     */
248    private float getDegreesForRotation(int value) {
249        switch (value) {
250        case Surface.ROTATION_90:
251            return 90f;
252        case Surface.ROTATION_180:
253            return 180f;
254        case Surface.ROTATION_270:
255            return 270f;
256        }
257        return 0f;
258    }
259
260    /**
261     * Takes a screenshot of the current display and shows an animation.
262     */
263    void takeScreenshot() {
264        // We need to orient the screenshot correctly (and the Surface api seems to take screenshots
265        // only in the natural orientation of the device :!)
266        mDisplay.getRealMetrics(mDisplayMetrics);
267        float[] dims = {mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels};
268        float degrees = getDegreesForRotation(mDisplay.getRotation());
269        boolean requiresRotation = (degrees > 0);
270        if (requiresRotation) {
271            // Get the dimensions of the device in its native orientation
272            mDisplayMatrix.reset();
273            mDisplayMatrix.preRotate(-degrees);
274            mDisplayMatrix.mapPoints(dims);
275            dims[0] = Math.abs(dims[0]);
276            dims[1] = Math.abs(dims[1]);
277        }
278        mScreenBitmap = Surface.screenshot((int) dims[0], (int) dims[1]);
279        if (requiresRotation) {
280            // Rotate the screenshot to the current orientation
281            Bitmap ss = Bitmap.createBitmap(mDisplayMetrics.widthPixels,
282                    mDisplayMetrics.heightPixels, Bitmap.Config.ARGB_8888);
283            Canvas c = new Canvas(ss);
284            c.translate(ss.getWidth() / 2, ss.getHeight() / 2);
285            c.rotate(360f - degrees);
286            c.translate(-dims[0] / 2, -dims[1] / 2);
287            c.drawBitmap(mScreenBitmap, 0, 0, null);
288            mScreenBitmap = ss;
289        }
290
291        // If we couldn't take the screenshot, notify the user
292        if (mScreenBitmap == null) {
293            Toast.makeText(mContext, R.string.screenshot_failed_toast,
294                    Toast.LENGTH_SHORT).show();
295            return;
296        }
297
298        // Start the post-screenshot animation
299        startAnimation();
300    }
301
302
303    /**
304     * Starts the animation after taking the screenshot
305     */
306    private void startAnimation() {
307        // Add the view for the animation
308        mScreenshotView.setImageBitmap(mScreenBitmap);
309        mScreenshotLayout.requestFocus();
310
311        // Setup the animation with the screenshot just taken
312        if (mScreenshotAnimation != null) {
313            mScreenshotAnimation.end();
314        }
315
316        mWindowManager.addView(mScreenshotLayout, mWindowLayoutParams);
317        ValueAnimator screenshotFadeInAnim = createScreenshotFadeInAnimation();
318        ValueAnimator screenshotFadeOutAnim = createScreenshotFadeOutAnimation();
319        mScreenshotAnimation = new AnimatorSet();
320        mScreenshotAnimation.play(screenshotFadeInAnim).before(screenshotFadeOutAnim);
321        mScreenshotAnimation.addListener(new AnimatorListenerAdapter() {
322            @Override
323            public void onAnimationEnd(Animator animation) {
324                // Save the screenshot once we have a bit of time now
325                saveScreenshotInWorkerThread();
326
327                mWindowManager.removeView(mScreenshotLayout);
328            }
329        });
330        mScreenshotAnimation.start();
331    }
332    private ValueAnimator createScreenshotFadeInAnimation() {
333        ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
334        anim.setInterpolator(mCubicInterpolator);
335        anim.setDuration(SCREENSHOT_FADE_IN_DURATION);
336        anim.addListener(new AnimatorListenerAdapter() {
337            @Override
338            public void onAnimationStart(Animator animation) {
339                mBackgroundView.setVisibility(View.VISIBLE);
340                mScreenshotContainerView.setVisibility(View.VISIBLE);
341            }
342        });
343        anim.addUpdateListener(new AnimatorUpdateListener() {
344            @Override
345            public void onAnimationUpdate(ValueAnimator animation) {
346                float t = ((Float) animation.getAnimatedValue()).floatValue();
347                mBackgroundView.setAlpha(mBackgroundViewAlphaInterpolator.getInterpolation(t) *
348                        BACKGROUND_ALPHA);
349                float scaleT = SCREENSHOT_SCALE + (1f - t) * SCREENSHOT_SCALE;
350                mScreenshotContainerView.setAlpha(t*t*t*t);
351                mScreenshotContainerView.setScaleX(scaleT);
352                mScreenshotContainerView.setScaleY(scaleT);
353                mScreenshotContainerView.setRotation(t * SCREENSHOT_ROTATION);
354            }
355        });
356        return anim;
357    }
358    private ValueAnimator createScreenshotFadeOutAnimation() {
359        ValueAnimator anim = ValueAnimator.ofFloat(1f, 0f);
360        anim.setInterpolator(mCubicInterpolator);
361        anim.setStartDelay(SCREENSHOT_FADE_OUT_DELAY);
362        anim.setDuration(SCREENSHOT_FADE_OUT_DURATION);
363        anim.addListener(new AnimatorListenerAdapter() {
364            @Override
365            public void onAnimationEnd(Animator animation) {
366                mBackgroundView.setVisibility(View.GONE);
367                mScreenshotContainerView.setVisibility(View.GONE);
368            }
369        });
370        anim.addUpdateListener(new AnimatorUpdateListener() {
371            @Override
372            public void onAnimationUpdate(ValueAnimator animation) {
373                float t = ((Float) animation.getAnimatedValue()).floatValue();
374                float scaleT = SCREENSHOT_MIN_SCALE +
375                        t*(SCREENSHOT_SCALE - SCREENSHOT_MIN_SCALE);
376                mScreenshotContainerView.setAlpha(t);
377                mScreenshotContainerView.setScaleX(scaleT);
378                mScreenshotContainerView.setScaleY(scaleT);
379                mBackgroundView.setAlpha(t * t * BACKGROUND_ALPHA);
380            }
381        });
382        return anim;
383    }
384}
385