Home | History | Annotate | Download | only in window_snapshot
      1 // Copyright (c) 2011 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.
      4 
      5 #include "chrome/browser/ui/window_snapshot/window_snapshot.h"
      6 
      7 #import <Cocoa/Cocoa.h>
      8 
      9 #include "base/logging.h"
     10 #include "base/mac/scoped_cftyperef.h"
     11 #include "base/memory/scoped_nsobject.h"
     12 #include "ui/gfx/rect.h"
     13 
     14 namespace browser {
     15 
     16 gfx::Rect GrabWindowSnapshot(gfx::NativeWindow window,
     17     std::vector<unsigned char>* png_representation) {
     18   png_representation->clear();
     19 
     20   // Make sure to grab the "window frame" view so we get current tab +
     21   // tabstrip.
     22   NSView* view = [[window contentView] superview];
     23   base::mac::ScopedCFTypeRef<CGImageRef> windowSnapshot(CGWindowListCreateImage(
     24       CGRectNull, kCGWindowListOptionIncludingWindow,
     25       [[view window] windowNumber], kCGWindowImageBoundsIgnoreFraming));
     26   if (CGImageGetWidth(windowSnapshot) <= 0)
     27     return gfx::Rect();
     28 
     29   scoped_nsobject<NSBitmapImageRep> rep(
     30       [[NSBitmapImageRep alloc] initWithCGImage:windowSnapshot]);
     31   NSData* data = [rep representationUsingType:NSPNGFileType properties:nil];
     32   const unsigned char* buf = static_cast<const unsigned char*>([data bytes]);
     33   NSUInteger length = [data length];
     34   if (buf == NULL || length == 0)
     35     return gfx::Rect();
     36 
     37   png_representation->assign(buf, buf + length);
     38   DCHECK(!png_representation->empty());
     39 
     40   return gfx::Rect(static_cast<int>([rep pixelsWide]),
     41                    static_cast<int>([rep pixelsHigh]));
     42 }
     43 
     44 }  // namespace browser
     45