1 /*
2  * Copyright (C) 2016 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.shell;
18 
19 import android.graphics.Bitmap;
20 import android.graphics.Point;
21 import android.graphics.Rect;
22 import android.hardware.display.DisplayManagerGlobal;
23 import android.util.Log;
24 import android.view.Display;
25 import android.view.SurfaceControl;
26 
27 /**
28  * Helper class used to take screenshots.
29  *
30  * TODO: logic below was copied and pasted from UiAutomation; it should be refactored into a common
31  * component that could be used by both (Shell and UiAutomation).
32  */
33 final class Screenshooter {
34 
35     private static final String TAG = "Screenshooter";
36 
37     /**
38      * Takes a screenshot.
39      *
40      * @return The screenshot bitmap on success, null otherwise.
41      */
takeScreenshot()42     static Bitmap takeScreenshot() {
43         Display display = DisplayManagerGlobal.getInstance()
44                 .getRealDisplay(Display.DEFAULT_DISPLAY);
45         Point displaySize = new Point();
46         display.getRealSize(displaySize);
47         final int displayWidth = displaySize.x;
48         final int displayHeight = displaySize.y;
49 
50         int rotation = display.getRotation();
51         Rect crop = new Rect(0, 0, displayWidth, displayHeight);
52         Log.d(TAG, "Taking screenshot of dimensions " + displayWidth + " x " + displayHeight);
53         // Take the screenshot
54         Bitmap screenShot =
55                 SurfaceControl.screenshot(crop, displayWidth, displayHeight, rotation);
56         if (screenShot == null) {
57             Log.e(TAG, "Failed to take screenshot of dimensions " + displayWidth + " x "
58                     + displayHeight);
59             return null;
60         }
61 
62         // Optimization
63         screenShot.setHasAlpha(false);
64 
65         return screenShot;
66     }
67 }
68