OSDN Git Service

Merge "Adjust tests to new android-support-test + espresso libraries."
[android-x86/frameworks-base.git] / cmds / screencap / screencap.cpp
1 /*
2  * Copyright (C) 2010 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 #include <errno.h>
18 #include <unistd.h>
19 #include <stdio.h>
20 #include <fcntl.h>
21 #include <stdlib.h>
22 #include <string.h>
23
24 #include <linux/fb.h>
25 #include <sys/ioctl.h>
26 #include <sys/mman.h>
27
28 #include <binder/ProcessState.h>
29
30 #include <gui/SurfaceComposerClient.h>
31 #include <gui/ISurfaceComposer.h>
32
33 #include <ui/DisplayInfo.h>
34 #include <ui/PixelFormat.h>
35
36 #include <system/graphics.h>
37
38 // TODO: Fix Skia.
39 #pragma GCC diagnostic push
40 #pragma GCC diagnostic ignored "-Wunused-parameter"
41 #include <SkImageEncoder.h>
42 #include <SkData.h>
43 #include <SkColorSpace.h>
44 #pragma GCC diagnostic pop
45
46 using namespace android;
47
48 static uint32_t DEFAULT_DISPLAY_ID = ISurfaceComposer::eDisplayIdMain;
49
50 #define COLORSPACE_UNKNOWN    0
51 #define COLORSPACE_SRGB       1
52 #define COLORSPACE_DISPLAY_P3 2
53
54 static void usage(const char* pname)
55 {
56     fprintf(stderr,
57             "usage: %s [-hp] [-d display-id] [FILENAME]\n"
58             "   -h: this message\n"
59             "   -p: save the file as a png.\n"
60             "   -d: specify the display id to capture, default %d.\n"
61             "If FILENAME ends with .png it will be saved as a png.\n"
62             "If FILENAME is not given, the results will be printed to stdout.\n",
63             pname, DEFAULT_DISPLAY_ID
64     );
65 }
66
67 static SkColorType flinger2skia(PixelFormat f)
68 {
69     switch (f) {
70         case PIXEL_FORMAT_RGB_565:
71             return kRGB_565_SkColorType;
72         default:
73             return kN32_SkColorType;
74     }
75 }
76
77 static sk_sp<SkColorSpace> dataSpaceToColorSpace(android_dataspace d)
78 {
79     switch (d) {
80         case HAL_DATASPACE_V0_SRGB:
81             return SkColorSpace::MakeSRGB();
82         case HAL_DATASPACE_DISPLAY_P3:
83             return SkColorSpace::MakeRGB(
84                     SkColorSpace::kSRGB_RenderTargetGamma, SkColorSpace::kDCIP3_D65_Gamut);
85         default:
86             return nullptr;
87     }
88 }
89
90 static uint32_t dataSpaceToInt(android_dataspace d)
91 {
92     switch (d) {
93         case HAL_DATASPACE_V0_SRGB:
94             return COLORSPACE_SRGB;
95         case HAL_DATASPACE_DISPLAY_P3:
96             return COLORSPACE_DISPLAY_P3;
97         default:
98             return COLORSPACE_UNKNOWN;
99     }
100 }
101
102 static status_t notifyMediaScanner(const char* fileName) {
103     String8 cmd("am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file://");
104     String8 fileUrl("\"");
105     fileUrl.append(fileName);
106     fileUrl.append("\"");
107     cmd.append(fileName);
108     cmd.append(" > /dev/null");
109     int result = system(cmd.string());
110     if (result < 0) {
111         fprintf(stderr, "Unable to broadcast intent for media scanner.\n");
112         return UNKNOWN_ERROR;
113     }
114     return NO_ERROR;
115 }
116
117 int main(int argc, char** argv)
118 {
119     // setThreadPoolMaxThreadCount(0) actually tells the kernel it's
120     // not allowed to spawn any additional threads, but we still spawn
121     // a binder thread from userspace when we call startThreadPool().
122     // See b/36066697 for rationale
123     ProcessState::self()->setThreadPoolMaxThreadCount(0);
124     ProcessState::self()->startThreadPool();
125
126     const char* pname = argv[0];
127     bool png = false;
128     int32_t displayId = DEFAULT_DISPLAY_ID;
129     int c;
130     while ((c = getopt(argc, argv, "phd:")) != -1) {
131         switch (c) {
132             case 'p':
133                 png = true;
134                 break;
135             case 'd':
136                 displayId = atoi(optarg);
137                 break;
138             case '?':
139             case 'h':
140                 usage(pname);
141                 return 1;
142         }
143     }
144     argc -= optind;
145     argv += optind;
146
147     int fd = -1;
148     const char* fn = NULL;
149     if (argc == 0) {
150         fd = dup(STDOUT_FILENO);
151     } else if (argc == 1) {
152         fn = argv[0];
153         fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0664);
154         if (fd == -1) {
155             fprintf(stderr, "Error opening file: %s (%s)\n", fn, strerror(errno));
156             return 1;
157         }
158         const int len = strlen(fn);
159         if (len >= 4 && 0 == strcmp(fn+len-4, ".png")) {
160             png = true;
161         }
162     }
163
164     if (fd == -1) {
165         usage(pname);
166         return 1;
167     }
168
169     void const* mapbase = MAP_FAILED;
170     ssize_t mapsize = -1;
171
172     void const* base = NULL;
173     uint32_t w, s, h, f;
174     android_dataspace d;
175     size_t size = 0;
176
177     // Maps orientations from DisplayInfo to ISurfaceComposer
178     static const uint32_t ORIENTATION_MAP[] = {
179         ISurfaceComposer::eRotateNone, // 0 == DISPLAY_ORIENTATION_0
180         ISurfaceComposer::eRotate270, // 1 == DISPLAY_ORIENTATION_90
181         ISurfaceComposer::eRotate180, // 2 == DISPLAY_ORIENTATION_180
182         ISurfaceComposer::eRotate90, // 3 == DISPLAY_ORIENTATION_270
183     };
184
185     ScreenshotClient screenshot;
186     sp<IBinder> display = SurfaceComposerClient::getBuiltInDisplay(displayId);
187     if (display == NULL) {
188         fprintf(stderr, "Unable to get handle for display %d\n", displayId);
189         return 1;
190     }
191
192     Vector<DisplayInfo> configs;
193     SurfaceComposerClient::getDisplayConfigs(display, &configs);
194     int activeConfig = SurfaceComposerClient::getActiveConfig(display);
195     if (static_cast<size_t>(activeConfig) >= configs.size()) {
196         fprintf(stderr, "Active config %d not inside configs (size %zu)\n",
197                 activeConfig, configs.size());
198         return 1;
199     }
200     uint8_t displayOrientation = configs[activeConfig].orientation;
201     uint32_t captureOrientation = ORIENTATION_MAP[displayOrientation];
202
203     status_t result = screenshot.update(display, Rect(),
204             0 /* reqWidth */, 0 /* reqHeight */,
205             INT32_MIN, INT32_MAX, /* all layers */
206             false, captureOrientation);
207     if (result == NO_ERROR) {
208         base = screenshot.getPixels();
209         w = screenshot.getWidth();
210         h = screenshot.getHeight();
211         s = screenshot.getStride();
212         f = screenshot.getFormat();
213         d = screenshot.getDataSpace();
214         size = screenshot.getSize();
215     }
216
217     if (base != NULL) {
218         if (png) {
219             const SkImageInfo info =
220                 SkImageInfo::Make(w, h, flinger2skia(f), kPremul_SkAlphaType,
221                     dataSpaceToColorSpace(d));
222             SkPixmap pixmap(info, base, s * bytesPerPixel(f));
223             struct FDWStream final : public SkWStream {
224               size_t fBytesWritten = 0;
225               int fFd;
226               FDWStream(int f) : fFd(f) {}
227               size_t bytesWritten() const override { return fBytesWritten; }
228               bool write(const void* buffer, size_t size) override {
229                 fBytesWritten += size;
230                 return size == 0 || ::write(fFd, buffer, size) > 0;
231               }
232             } fdStream(fd);
233             (void)SkEncodeImage(&fdStream, pixmap, SkEncodedImageFormat::kPNG, 100);
234             if (fn != NULL) {
235                 notifyMediaScanner(fn);
236             }
237         } else {
238             uint32_t c = dataSpaceToInt(d);
239             write(fd, &w, 4);
240             write(fd, &h, 4);
241             write(fd, &f, 4);
242             write(fd, &c, 4);
243             size_t Bpp = bytesPerPixel(f);
244             for (size_t y=0 ; y<h ; y++) {
245                 write(fd, base, w*Bpp);
246                 base = (void *)((char *)base + s*Bpp);
247             }
248         }
249     }
250     close(fd);
251     if (mapbase != MAP_FAILED) {
252         munmap((void *)mapbase, mapsize);
253     }
254
255     // b/36066697: Avoid running static destructors.
256     _exit(0);
257 }