1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/snapshot/snapshot.h"
7 #include "base/logging.h"
8 #include "base/safe_numerics.h"
9 #include "third_party/skia/include/core/SkBitmap.h"
10 #include "third_party/skia/include/core/SkPixelRef.h"
11 #include "ui/aura/root_window.h"
12 #include "ui/aura/window.h"
13 #include "ui/compositor/compositor.h"
14 #include "ui/compositor/dip_util.h"
15 #include "ui/compositor/layer.h"
16 #include "ui/gfx/codec/png_codec.h"
17 #include "ui/gfx/display.h"
18 #include "ui/gfx/rect.h"
19 #include "ui/gfx/rect_conversions.h"
20 #include "ui/gfx/rect_f.h"
21 #include "ui/gfx/screen.h"
22 #include "ui/gfx/skbitmap_operations.h"
23 #include "ui/gfx/transform.h"
27 bool GrabViewSnapshot(gfx::NativeView view,
28 std::vector<unsigned char>* png_representation,
29 const gfx::Rect& snapshot_bounds) {
30 return GrabWindowSnapshot(view, png_representation, snapshot_bounds);
33 bool GrabWindowSnapshot(gfx::NativeWindow window,
34 std::vector<unsigned char>* png_representation,
35 const gfx::Rect& snapshot_bounds) {
36 ui::Compositor* compositor = window->layer()->GetCompositor();
38 gfx::RectF read_pixels_bounds = snapshot_bounds;
40 // We must take into account the window's position on the desktop.
41 read_pixels_bounds.Offset(
42 window->GetBoundsInRootWindow().origin().OffsetFromOrigin());
43 aura::WindowEventDispatcher* dispatcher = window->GetDispatcher();
45 dispatcher->GetRootTransform().TransformRect(&read_pixels_bounds);
47 gfx::Rect read_pixels_bounds_in_pixel =
48 gfx::ToEnclosingRect(read_pixels_bounds);
50 // Sometimes (i.e. when using Aero on Windows) the compositor's size is
51 // smaller than the window bounds. So trim appropriately.
52 read_pixels_bounds_in_pixel.Intersect(gfx::Rect(compositor->size()));
54 DCHECK_LE(0, read_pixels_bounds.x());
55 DCHECK_LE(0, read_pixels_bounds.y());
58 if (!compositor->ReadPixels(&bitmap, read_pixels_bounds_in_pixel))
61 gfx::Display display =
62 gfx::Screen::GetScreenFor(window)->GetDisplayNearestWindow(window);
63 switch (display.rotation()) {
64 case gfx::Display::ROTATE_0:
66 case gfx::Display::ROTATE_90:
67 bitmap = SkBitmapOperations::Rotate(
68 bitmap, SkBitmapOperations::ROTATION_270_CW);
70 case gfx::Display::ROTATE_180:
71 bitmap = SkBitmapOperations::Rotate(
72 bitmap, SkBitmapOperations::ROTATION_180_CW);
74 case gfx::Display::ROTATE_270:
75 bitmap = SkBitmapOperations::Rotate(
76 bitmap, SkBitmapOperations::ROTATION_90_CW);
80 unsigned char* pixels = reinterpret_cast<unsigned char*>(
81 bitmap.pixelRef()->pixels());
82 gfx::PNGCodec::Encode(pixels, gfx::PNGCodec::FORMAT_BGRA,
83 gfx::Size(bitmap.width(), bitmap.height()),
84 base::checked_numeric_cast<int>(bitmap.rowBytes()),
85 true, std::vector<gfx::PNGCodec::Comment>(),