summaryrefslogtreecommitdiffstats
path: root/app
diff options
context:
space:
mode:
Diffstat (limited to 'app')
-rw-r--r--app/app_base.gypi14
-rw-r--r--app/surface/accelerated_surface_mac.cc334
-rw-r--r--app/surface/accelerated_surface_mac.h108
-rw-r--r--app/surface/io_surface_support_mac.cc242
-rw-r--r--app/surface/io_surface_support_mac.h66
-rw-r--r--app/surface/transport_dib.h156
-rw-r--r--app/surface/transport_dib_linux.cc113
-rw-r--r--app/surface/transport_dib_mac.cc77
-rw-r--r--app/surface/transport_dib_win.cc81
-rw-r--r--app/x11_util.cc751
-rw-r--r--app/x11_util.h173
-rw-r--r--app/x11_util_internal.h35
12 files changed, 2150 insertions, 0 deletions
diff --git a/app/app_base.gypi b/app/app_base.gypi
index b417256..0f6f363 100644
--- a/app/app_base.gypi
+++ b/app/app_base.gypi
@@ -50,6 +50,9 @@
'gtk_signal.h',
'gtk_util.cc',
'gtk_util.h',
+ 'x11_util.cc',
+ 'x11_util.h',
+ 'x11_util_internal.h',
],
}],
],
@@ -163,6 +166,14 @@
'sql/statement.h',
'sql/transaction.cc',
'sql/transaction.h',
+ 'surface/accelerated_surface_mac.cc',
+ 'surface/accelerated_surface_mac.h',
+ 'surface/io_surface_support_mac.cc',
+ 'surface/io_surface_support_mac.h',
+ 'surface/transport_dib.h',
+ 'surface/transport_dib_linux.cc',
+ 'surface/transport_dib_mac.cc',
+ 'surface/transport_dib_win.cc',
'table_model.cc',
'table_model.h',
'table_model_observer.h',
@@ -172,6 +183,9 @@
'theme_provider.h',
'throb_animation.cc',
'throb_animation.h',
+ 'x11_util.cc',
+ 'x11_util.h',
+ 'x11_util_internal.h',
],
'conditions': [
['OS=="linux" or OS=="freebsd" or OS=="openbsd"', {
diff --git a/app/surface/accelerated_surface_mac.cc b/app/surface/accelerated_surface_mac.cc
new file mode 100644
index 0000000..f50d528
--- /dev/null
+++ b/app/surface/accelerated_surface_mac.cc
@@ -0,0 +1,334 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "app/surface/accelerated_surface_mac.h"
+
+#include "app/surface/io_surface_support_mac.h"
+#include "base/logging.h"
+#include "gfx/rect.h"
+
+AcceleratedSurface::AcceleratedSurface()
+ : gl_context_(NULL),
+ pbuffer_(NULL),
+ surface_width_(0),
+ surface_height_(0),
+ texture_(0),
+ fbo_(0),
+ depth_stencil_renderbuffer_(0),
+ bound_fbo_(0),
+ bound_renderbuffer_(0) {
+}
+
+bool AcceleratedSurface::Initialize() {
+ // Create a 1x1 pbuffer and associated context to bootstrap things
+ static const CGLPixelFormatAttribute attribs[] = {
+ (CGLPixelFormatAttribute) kCGLPFAPBuffer,
+ (CGLPixelFormatAttribute) 0
+ };
+ CGLPixelFormatObj pixel_format;
+ GLint num_pixel_formats;
+ if (CGLChoosePixelFormat(attribs,
+ &pixel_format,
+ &num_pixel_formats) != kCGLNoError) {
+ DLOG(ERROR) << "Error choosing pixel format.";
+ return false;
+ }
+ if (!pixel_format) {
+ return false;
+ }
+ CGLContextObj context;
+ CGLError res = CGLCreateContext(pixel_format, 0, &context);
+ CGLDestroyPixelFormat(pixel_format);
+ if (res != kCGLNoError) {
+ DLOG(ERROR) << "Error creating context.";
+ return false;
+ }
+ CGLPBufferObj pbuffer;
+ if (CGLCreatePBuffer(1, 1,
+ GL_TEXTURE_2D, GL_RGBA,
+ 0, &pbuffer) != kCGLNoError) {
+ CGLDestroyContext(context);
+ DLOG(ERROR) << "Error creating pbuffer.";
+ return false;
+ }
+ if (CGLSetPBuffer(context, pbuffer, 0, 0, 0) != kCGLNoError) {
+ CGLDestroyContext(context);
+ CGLDestroyPBuffer(pbuffer);
+ DLOG(ERROR) << "Error attaching pbuffer to context.";
+ return false;
+ }
+ gl_context_ = context;
+ pbuffer_ = pbuffer;
+ // Now we're ready to handle SetWindowSize calls, which will
+ // allocate and/or reallocate the IOSurface and associated offscreen
+ // OpenGL structures for rendering.
+ return true;
+}
+
+void AcceleratedSurface::Destroy() {
+ // Release the old TransportDIB in the browser.
+ if (dib_free_callback_.get() && transport_dib_.get()) {
+ dib_free_callback_->Run(transport_dib_->id());
+ }
+ transport_dib_.reset();
+ if (gl_context_)
+ CGLDestroyContext(gl_context_);
+ if (pbuffer_)
+ CGLDestroyPBuffer(pbuffer_);
+}
+
+// Call after making changes to the surface which require a visual update.
+// Makes the rendering show up in other processes.
+void AcceleratedSurface::SwapBuffers() {
+ if (bound_fbo_ != fbo_) {
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo_);
+ }
+ if (io_surface_.get() != NULL) {
+ // Bind and unbind the framebuffer to make changes to the
+ // IOSurface show up in the other process.
+ glFlush();
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo_);
+ } else if (transport_dib_.get() != NULL) {
+ // Pre-Mac OS X 10.6, fetch the rendered image from the FBO and copy it
+ // into the TransportDIB.
+ // TODO(dspringer): There are a couple of options that can speed this up.
+ // First is to use async reads into a PBO, second is to use SPI that
+ // allows many tasks to access the same CGSSurface.
+ void* pixel_memory = transport_dib_->memory();
+ if (pixel_memory) {
+ // Note that glReadPixels does an implicit glFlush().
+ glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
+ glReadPixels(0,
+ 0,
+ surface_width_,
+ surface_height_,
+ GL_BGRA, // This pixel format should have no conversion.
+ GL_UNSIGNED_INT_8_8_8_8_REV,
+ pixel_memory);
+ }
+ }
+ if (bound_fbo_ != fbo_) {
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, bound_fbo_);
+ }
+}
+
+static void AddBooleanValue(CFMutableDictionaryRef dictionary,
+ const CFStringRef key,
+ bool value) {
+ CFDictionaryAddValue(dictionary, key,
+ (value ? kCFBooleanTrue : kCFBooleanFalse));
+}
+
+static void AddIntegerValue(CFMutableDictionaryRef dictionary,
+ const CFStringRef key,
+ int32 value) {
+ CFNumberRef number = CFNumberCreate(NULL, kCFNumberSInt32Type, &value);
+ CFDictionaryAddValue(dictionary, key, number);
+}
+
+void AcceleratedSurface::AllocateRenderBuffers(GLenum target,
+ int32 width, int32 height) {
+ if (!texture_) {
+ // Generate the texture object.
+ glGenTextures(1, &texture_);
+ glBindTexture(target, texture_);
+ glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+ // Generate and bind the framebuffer object.
+ glGenFramebuffersEXT(1, &fbo_);
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo_);
+ bound_fbo_ = fbo_;
+ // Generate (but don't bind) the depth buffer -- we don't need
+ // this bound in order to do offscreen rendering.
+ glGenRenderbuffersEXT(1, &depth_stencil_renderbuffer_);
+ }
+
+ // Reallocate the depth buffer.
+ glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth_stencil_renderbuffer_);
+ glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT,
+ GL_DEPTH24_STENCIL8_EXT,
+ width,
+ height);
+
+ // Unbind the renderbuffers.
+ glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, bound_renderbuffer_);
+
+ // Make sure that subsequent set-up code affects the render texture.
+ glBindTexture(target, texture_);
+}
+
+bool AcceleratedSurface::SetupFrameBufferObject(GLenum target) {
+ if (bound_fbo_ != fbo_) {
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo_);
+ }
+ GLenum fbo_status;
+ glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
+ GL_COLOR_ATTACHMENT0_EXT,
+ target,
+ texture_,
+ 0);
+ fbo_status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
+ if (fbo_status == GL_FRAMEBUFFER_COMPLETE_EXT) {
+ glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,
+ GL_DEPTH_ATTACHMENT_EXT,
+ GL_RENDERBUFFER_EXT,
+ depth_stencil_renderbuffer_);
+ fbo_status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
+ }
+ // Attach the depth and stencil buffer.
+ if (fbo_status == GL_FRAMEBUFFER_COMPLETE_EXT) {
+ glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,
+ 0x8D20, // GL_STENCIL_ATTACHMENT,
+ GL_RENDERBUFFER_EXT,
+ depth_stencil_renderbuffer_);
+ fbo_status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
+ }
+ if (bound_fbo_ != fbo_) {
+ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, bound_fbo_);
+ }
+ return fbo_status == GL_FRAMEBUFFER_COMPLETE_EXT;
+}
+
+bool AcceleratedSurface::MakeCurrent() {
+ if (CGLGetCurrentContext() != gl_context_) {
+ if (CGLSetCurrentContext(gl_context_) != kCGLNoError) {
+ DLOG(ERROR) << "Unable to make gl context current.";
+ return false;
+ }
+ }
+ return true;
+}
+
+void AcceleratedSurface::Clear(const gfx::Rect& rect) {
+ glClearColor(1.0, 1.0, 1.0, 1.0);
+ glViewport(0, 0, rect.width(), rect.height());
+ glMatrixMode(GL_PROJECTION);
+ glLoadIdentity();
+ glOrtho(0, rect.width(), 0, rect.height(), -1, 1);
+ glClear(GL_COLOR_BUFFER_BIT);
+}
+
+uint64 AcceleratedSurface::SetSurfaceSize(int32 width, int32 height) {
+ if (surface_width_ == width && surface_height_ == height) {
+ // Return 0 to indicate to the caller that no new backing store
+ // allocation occurred.
+ return 0;
+ }
+
+ IOSurfaceSupport* io_surface_support = IOSurfaceSupport::Initialize();
+ if (!io_surface_support)
+ return 0; // Caller can try using SetWindowSizeForTransportDIB().
+
+ if (!MakeCurrent())
+ return 0;
+
+ // GL_TEXTURE_RECTANGLE_ARB is the best supported render target on
+ // Mac OS X and is required for IOSurface interoperability.
+ GLenum target = GL_TEXTURE_RECTANGLE_ARB;
+ AllocateRenderBuffers(target, width, height);
+
+ // Allocate a new IOSurface, which is the GPU resource that can be
+ // shared across processes.
+ scoped_cftyperef<CFMutableDictionaryRef> properties;
+ properties.reset(CFDictionaryCreateMutable(kCFAllocatorDefault,
+ 0,
+ &kCFTypeDictionaryKeyCallBacks,
+ &kCFTypeDictionaryValueCallBacks));
+ AddIntegerValue(properties,
+ io_surface_support->GetKIOSurfaceWidth(), width);
+ AddIntegerValue(properties,
+ io_surface_support->GetKIOSurfaceHeight(), height);
+ AddIntegerValue(properties,
+ io_surface_support->GetKIOSurfaceBytesPerElement(), 4);
+ AddBooleanValue(properties,
+ io_surface_support->GetKIOSurfaceIsGlobal(), true);
+ // I believe we should be able to unreference the IOSurfaces without
+ // synchronizing with the browser process because they are
+ // ultimately reference counted by the operating system.
+ io_surface_.reset(io_surface_support->IOSurfaceCreate(properties));
+
+ // Don't think we need to identify a plane.
+ GLuint plane = 0;
+ io_surface_support->CGLTexImageIOSurface2D(gl_context_,
+ target,
+ GL_RGBA,
+ width,
+ height,
+ GL_BGRA,
+ GL_UNSIGNED_INT_8_8_8_8_REV,
+ io_surface_.get(),
+ plane);
+ // Set up the frame buffer object.
+ SetupFrameBufferObject(target);
+ surface_width_ = width;
+ surface_height_ = height;
+
+ // Now send back an identifier for the IOSurface. We originally
+ // intended to send back a mach port from IOSurfaceCreateMachPort
+ // but it looks like Chrome IPC would need to be modified to
+ // properly send mach ports between processes. For the time being we
+ // make our IOSurfaces global and send back their identifiers. On
+ // the browser process side the identifier is reconstituted into an
+ // IOSurface for on-screen rendering.
+ return io_surface_support->IOSurfaceGetID(io_surface_);
+}
+
+TransportDIB::Handle AcceleratedSurface::SetTransportDIBSize(
+ int32 width, int32 height) {
+ if (surface_width_ == width && surface_height_ == height) {
+ // Return an invalid handle to indicate to the caller that no new backing
+ // store allocation occurred.
+ return TransportDIB::DefaultHandleValue();
+ }
+ surface_width_ = width;
+ surface_height_ = height;
+
+ // Release the old TransportDIB in the browser.
+ if (dib_free_callback_.get() && transport_dib_.get()) {
+ dib_free_callback_->Run(transport_dib_->id());
+ }
+ transport_dib_.reset();
+
+ // Ask the renderer to create a TransportDIB.
+ size_t dib_size = width * 4 * height; // 4 bytes per pixel.
+ TransportDIB::Handle dib_handle;
+ if (dib_alloc_callback_.get()) {
+ dib_alloc_callback_->Run(dib_size, &dib_handle);
+ }
+ if (!TransportDIB::is_valid(dib_handle)) {
+ // If the allocator fails, it means the DIB was not created in the browser,
+ // so there is no need to run the deallocator here.
+ return TransportDIB::DefaultHandleValue();
+ }
+ transport_dib_.reset(TransportDIB::Map(dib_handle));
+ if (transport_dib_.get() == NULL) {
+ // TODO(dspringer): if the Map() fails, should the deallocator be run so
+ // that the DIB is deallocated in the browser?
+ return TransportDIB::DefaultHandleValue();
+ }
+
+ // Set up the render buffers and reserve enough space on the card for the
+ // framebuffer texture.
+ GLenum target = GL_TEXTURE_RECTANGLE_ARB;
+ AllocateRenderBuffers(target, width, height);
+ glTexImage2D(target,
+ 0, // mipmap level 0
+ GL_RGBA8, // internal pixel format
+ width,
+ height,
+ 0, // 0 border
+ GL_BGRA, // Used for consistency
+ GL_UNSIGNED_INT_8_8_8_8_REV,
+ NULL); // No data, just reserve room on the card.
+ SetupFrameBufferObject(target);
+ return transport_dib_->handle();
+}
+
+void AcceleratedSurface::SetTransportDIBAllocAndFree(
+ Callback2<size_t, TransportDIB::Handle*>::Type* allocator,
+ Callback1<TransportDIB::Id>::Type* deallocator) {
+ dib_alloc_callback_.reset(allocator);
+ dib_free_callback_.reset(deallocator);
+}
diff --git a/app/surface/accelerated_surface_mac.h b/app/surface/accelerated_surface_mac.h
new file mode 100644
index 0000000..32cd0df
--- /dev/null
+++ b/app/surface/accelerated_surface_mac.h
@@ -0,0 +1,108 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef APP_SURFACE_ACCELERATED_SURFACE_MAC_H_
+#define APP_SURFACE_ACCELERATED_SURFACE_MAC_H_
+
+#include <CoreFoundation/CoreFoundation.h>
+#include <OpenGL/OpenGL.h>
+
+#include "app/surface/transport_dib.h"
+#include "base/callback.h"
+#include "base/scoped_cftyperef.h"
+#include "base/scoped_ptr.h"
+
+namespace gfx {
+class Rect;
+}
+
+// Encapsulates an accelerated GL surface that can be shared across processes
+// on systems that support it (10.6 and above). For systems that do not, it
+// uses a regular dib. There will either be a GL Context or a TransportDIB,
+// never both.
+
+class AcceleratedSurface {
+ public:
+ AcceleratedSurface();
+ virtual ~AcceleratedSurface() { }
+
+ // Set up internal buffers. Returns false upon failure.
+ bool Initialize();
+ // Tear down. Must be called before destructor to prevent leaks.
+ void Destroy();
+
+ // These methods are used only when there is a GL surface.
+
+ // Sets the accelerated surface to the given size, creating a new one if
+ // the height or width changes. Returns a unique id of the IOSurface to
+ // which the surface is bound, or 0 if no changes were made or an error
+ // occurred. MakeCurrent() will have been called on the new surface.
+ uint64 SetSurfaceSize(int32 width, int32 height);
+ // Sets the GL context to be the current one for drawing. Returns true if
+ // it succeeded.
+ bool MakeCurrent();
+ // Clear the surface to all white. Assumes the caller has already called
+ // MakeCurrent().
+ void Clear(const gfx::Rect& rect);
+ // Call after making changes to the surface which require a visual update.
+ // Makes the rendering show up in other processes.
+ void SwapBuffers();
+ CGLContextObj context() { return gl_context_; }
+
+ // These methods are only used when there is a transport DIB.
+
+ // Sets the transport DIB to the given size, creating a new one if the
+ // height or width changes. Returns a handle to the new DIB, or a default
+ // handle if no changes were made.
+ TransportDIB::Handle SetTransportDIBSize(int32 width, int32 height);
+ // Sets the methods to use for allocating and freeing memory for the
+ // transport DIB.
+ void SetTransportDIBAllocAndFree(
+ Callback2<size_t, TransportDIB::Handle*>::Type* allocator,
+ Callback1<TransportDIB::Id>::Type* deallocator);
+
+ private:
+ // Helper function to generate names for the backing texture, render buffers
+ // and FBO. On return, the resulting buffer names can be attached to |fbo_|.
+ // |target| is the target type for the color buffer.
+ void AllocateRenderBuffers(GLenum target, int32 width, int32 height);
+
+ // Helper function to attach the buffers previously allocated by a call to
+ // AllocateRenderBuffers(). On return, |fbo_| can be used for
+ // rendering. |target| must be the same value as used in the call to
+ // AllocateRenderBuffers(). Returns |true| if the resulting framebuffer
+ // object is valid.
+ bool SetupFrameBufferObject(GLenum target);
+
+ CGLContextObj gl_context_;
+ CGLPBufferObj pbuffer_;
+ // Either |io_surface_| or |transport_dib_| is a valid pointer, but not both.
+ // |io_surface_| is non-NULL if the IOSurface APIs are supported (Mac OS X
+ // 10.6 and later).
+ // TODO(dspringer,kbr): Should the GPU backing store be encapsulated in its
+ // own class so all this implementation detail is hidden?
+ scoped_cftyperef<CFTypeRef> io_surface_;
+ // TODO(dspringer): If we end up keeping this TransportDIB mechanism, this
+ // should really be a scoped_ptr_malloc<>, with a deallocate functor that
+ // runs |dib_free_callback_|. I was not able to figure out how to
+ // make this work (or even compile).
+ scoped_ptr<TransportDIB> transport_dib_;
+ int32 surface_width_;
+ int32 surface_height_;
+ GLuint texture_;
+ GLuint fbo_;
+ GLuint depth_stencil_renderbuffer_;
+ // For tracking whether the default framebuffer / renderbuffer or
+ // ones created by the end user are currently bound
+ // TODO(kbr): Need to property hook up and track the OpenGL state and hook
+ // up the notion of the currently bound FBO.
+ GLuint bound_fbo_;
+ GLuint bound_renderbuffer_;
+ // Allocate a TransportDIB in the renderer.
+ scoped_ptr<Callback2<size_t, TransportDIB::Handle*>::Type>
+ dib_alloc_callback_;
+ scoped_ptr<Callback1<TransportDIB::Id>::Type> dib_free_callback_;
+};
+
+#endif // APP_SURFACE_ACCELERATED_SURFACE_MAC_H_
diff --git a/app/surface/io_surface_support_mac.cc b/app/surface/io_surface_support_mac.cc
new file mode 100644
index 0000000..fed66602
--- /dev/null
+++ b/app/surface/io_surface_support_mac.cc
@@ -0,0 +1,242 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <dlfcn.h>
+
+#include "base/singleton.h"
+#include "app/surface/io_surface_support_mac.h"
+
+typedef CFTypeRef (*IOSurfaceCreateProcPtr)(CFDictionaryRef properties);
+typedef uint32 (*IOSurfaceGetIDProcPtr)(CFTypeRef io_surface);
+typedef CFTypeRef (*IOSurfaceLookupProcPtr)(uint32 io_surface_id);
+typedef mach_port_t (*IOSurfaceCreateMachPortProcPtr)(CFTypeRef io_surface);
+typedef CFTypeRef (*IOSurfaceLookupFromMachPortProcPtr)(mach_port_t port);
+typedef CGLError (*CGLTexImageIOSurface2DProcPtr)(CGLContextObj ctx,
+ GLenum target,
+ GLenum internal_format,
+ GLsizei width,
+ GLsizei height,
+ GLenum format,
+ GLenum type,
+ CFTypeRef io_surface,
+ GLuint plane);
+
+class IOSurfaceSupportImpl : public IOSurfaceSupport {
+ public:
+ static IOSurfaceSupportImpl* Initialize();
+
+ bool InitializedSuccessfully() {
+ return initialized_successfully_;
+ }
+
+ virtual CFStringRef GetKIOSurfaceWidth();
+ virtual CFStringRef GetKIOSurfaceHeight();
+ virtual CFStringRef GetKIOSurfaceBytesPerElement();
+ virtual CFStringRef GetKIOSurfaceIsGlobal();
+
+ virtual CFTypeRef IOSurfaceCreate(CFDictionaryRef properties);
+ virtual uint32 IOSurfaceGetID(CFTypeRef io_surface);
+ virtual CFTypeRef IOSurfaceLookup(uint32 io_surface_id);
+ virtual mach_port_t IOSurfaceCreateMachPort(CFTypeRef io_surface);
+ virtual CFTypeRef IOSurfaceLookupFromMachPort(mach_port_t port);
+
+ virtual CGLError CGLTexImageIOSurface2D(CGLContextObj ctx,
+ GLenum target,
+ GLenum internal_format,
+ GLsizei width,
+ GLsizei height,
+ GLenum format,
+ GLenum type,
+ CFTypeRef io_surface,
+ GLuint plane);
+
+ private:
+ IOSurfaceSupportImpl();
+ ~IOSurfaceSupportImpl();
+
+ void* iosurface_handle_;
+ void* opengl_handle_;
+ CFStringRef k_io_surface_width_;
+ CFStringRef k_io_surface_height_;
+ CFStringRef k_io_surface_bytes_per_element_;
+ CFStringRef k_io_surface_is_global_;
+ IOSurfaceCreateProcPtr io_surface_create_;
+ IOSurfaceGetIDProcPtr io_surface_get_id_;
+ IOSurfaceLookupProcPtr io_surface_lookup_;
+ IOSurfaceCreateMachPortProcPtr io_surface_create_mach_port_;
+ IOSurfaceLookupFromMachPortProcPtr io_surface_lookup_from_mach_port_;
+ CGLTexImageIOSurface2DProcPtr cgl_tex_image_io_surface_2d_;
+ bool initialized_successfully_;
+
+ friend struct DefaultSingletonTraits<IOSurfaceSupportImpl>;
+ DISALLOW_EVIL_CONSTRUCTORS(IOSurfaceSupportImpl);
+};
+
+static Singleton<IOSurfaceSupportImpl> sole_instance_;
+
+IOSurfaceSupportImpl* IOSurfaceSupportImpl::Initialize() {
+ IOSurfaceSupportImpl* impl = sole_instance_.get();
+ if (impl->InitializedSuccessfully())
+ return impl;
+ return NULL;
+}
+
+CFStringRef IOSurfaceSupportImpl::GetKIOSurfaceWidth() {
+ return k_io_surface_width_;
+}
+
+CFStringRef IOSurfaceSupportImpl::GetKIOSurfaceHeight() {
+ return k_io_surface_height_;
+}
+
+CFStringRef IOSurfaceSupportImpl::GetKIOSurfaceBytesPerElement() {
+ return k_io_surface_bytes_per_element_;
+}
+
+CFStringRef IOSurfaceSupportImpl::GetKIOSurfaceIsGlobal() {
+ return k_io_surface_is_global_;
+}
+
+CFTypeRef IOSurfaceSupportImpl::IOSurfaceCreate(CFDictionaryRef properties) {
+ return io_surface_create_(properties);
+}
+
+uint32 IOSurfaceSupportImpl::IOSurfaceGetID(
+ CFTypeRef io_surface) {
+ return io_surface_get_id_(io_surface);
+}
+
+CFTypeRef IOSurfaceSupportImpl::IOSurfaceLookup(uint32 io_surface_id) {
+ return io_surface_lookup_(io_surface_id);
+}
+
+mach_port_t IOSurfaceSupportImpl::IOSurfaceCreateMachPort(
+ CFTypeRef io_surface) {
+ return io_surface_create_mach_port_(io_surface);
+}
+
+CFTypeRef IOSurfaceSupportImpl::IOSurfaceLookupFromMachPort(mach_port_t port) {
+ return io_surface_lookup_from_mach_port_(port);
+}
+
+CGLError IOSurfaceSupportImpl::CGLTexImageIOSurface2D(CGLContextObj ctx,
+ GLenum target,
+ GLenum internal_format,
+ GLsizei width,
+ GLsizei height,
+ GLenum format,
+ GLenum type,
+ CFTypeRef io_surface,
+ GLuint plane) {
+ return cgl_tex_image_io_surface_2d_(ctx,
+ target,
+ internal_format,
+ width,
+ height,
+ format,
+ type,
+ io_surface,
+ plane);
+}
+
+IOSurfaceSupportImpl::IOSurfaceSupportImpl()
+ : iosurface_handle_(NULL),
+ opengl_handle_(NULL),
+ k_io_surface_width_(NULL),
+ k_io_surface_height_(NULL),
+ k_io_surface_bytes_per_element_(NULL),
+ k_io_surface_is_global_(NULL),
+ io_surface_create_(NULL),
+ io_surface_get_id_(NULL),
+ io_surface_lookup_(NULL),
+ io_surface_create_mach_port_(NULL),
+ io_surface_lookup_from_mach_port_(NULL),
+ cgl_tex_image_io_surface_2d_(NULL),
+ initialized_successfully_(false) {
+ iosurface_handle_ = dlopen(
+ "/System/Library/Frameworks/IOSurface.framework/IOSurface",
+ RTLD_LAZY | RTLD_LOCAL);
+ if (!iosurface_handle_)
+ return;
+ opengl_handle_ = dlopen(
+ "/System/Library/Frameworks/OpenGL.framework/OpenGL",
+ RTLD_LAZY | RTLD_LOCAL);
+ if (!opengl_handle_) {
+ dlclose(iosurface_handle_);
+ iosurface_handle_ = NULL;
+ return;
+ }
+
+ void* surface_width_ptr = dlsym(iosurface_handle_, "kIOSurfaceWidth");
+ void* surface_height_ptr = dlsym(iosurface_handle_, "kIOSurfaceHeight");
+ void* surface_bytes_per_element_ptr =
+ dlsym(iosurface_handle_, "kIOSurfaceBytesPerElement");
+ void* surface_is_global_ptr =
+ dlsym(iosurface_handle_, "kIOSurfaceIsGlobal");
+ void* surface_create_ptr = dlsym(iosurface_handle_, "IOSurfaceCreate");
+ void* surface_get_id_ptr = dlsym(iosurface_handle_, "IOSurfaceGetID");
+ void* surface_lookup_ptr = dlsym(iosurface_handle_, "IOSurfaceLookup");
+ void* surface_create_mach_port_ptr =
+ dlsym(iosurface_handle_, "IOSurfaceCreateMachPort");
+ void* surface_lookup_from_mach_port_ptr =
+ dlsym(iosurface_handle_, "IOSurfaceLookupFromMachPort");
+ void* tex_image_io_surface_2d_ptr =
+ dlsym(opengl_handle_, "CGLTexImageIOSurface2D");
+ if (!surface_width_ptr ||
+ !surface_height_ptr ||
+ !surface_bytes_per_element_ptr ||
+ !surface_is_global_ptr ||
+ !surface_create_ptr ||
+ !surface_get_id_ptr ||
+ !surface_lookup_ptr ||
+ !surface_create_mach_port_ptr ||
+ !surface_lookup_from_mach_port_ptr ||
+ !tex_image_io_surface_2d_ptr) {
+ dlclose(iosurface_handle_);
+ iosurface_handle_ = NULL;
+ dlclose(opengl_handle_);
+ opengl_handle_ = NULL;
+ return;
+ }
+
+ k_io_surface_width_ = *static_cast<CFStringRef*>(surface_width_ptr);
+ k_io_surface_height_ = *static_cast<CFStringRef*>(surface_height_ptr);
+ k_io_surface_bytes_per_element_ =
+ *static_cast<CFStringRef*>(surface_bytes_per_element_ptr);
+ k_io_surface_is_global_ = *static_cast<CFStringRef*>(surface_is_global_ptr);
+ io_surface_create_ = reinterpret_cast<IOSurfaceCreateProcPtr>(
+ surface_create_ptr);
+ io_surface_get_id_ =
+ reinterpret_cast<IOSurfaceGetIDProcPtr>(surface_get_id_ptr);
+ io_surface_lookup_ =
+ reinterpret_cast<IOSurfaceLookupProcPtr>(surface_lookup_ptr);
+ io_surface_create_mach_port_ =
+ reinterpret_cast<IOSurfaceCreateMachPortProcPtr>(
+ surface_create_mach_port_ptr);
+ io_surface_lookup_from_mach_port_ =
+ reinterpret_cast<IOSurfaceLookupFromMachPortProcPtr>(
+ surface_lookup_from_mach_port_ptr);
+ cgl_tex_image_io_surface_2d_ =
+ reinterpret_cast<CGLTexImageIOSurface2DProcPtr>(
+ tex_image_io_surface_2d_ptr);
+ initialized_successfully_ = true;
+}
+
+IOSurfaceSupportImpl::~IOSurfaceSupportImpl() {
+ if (iosurface_handle_)
+ dlclose(iosurface_handle_);
+ if (opengl_handle_)
+ dlclose(opengl_handle_);
+}
+
+IOSurfaceSupport* IOSurfaceSupport::Initialize() {
+ return IOSurfaceSupportImpl::Initialize();
+}
+
+IOSurfaceSupport::IOSurfaceSupport() {
+}
+
+IOSurfaceSupport::~IOSurfaceSupport() {
+}
+
diff --git a/app/surface/io_surface_support_mac.h b/app/surface/io_surface_support_mac.h
new file mode 100644
index 0000000..7386490
--- /dev/null
+++ b/app/surface/io_surface_support_mac.h
@@ -0,0 +1,66 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef APP_SURFACE_IO_SURFACE_SUPPORT_MAC_H_
+#define APP_SURFACE_IO_SURFACE_SUPPORT_MAC_H_
+
+#include <CoreFoundation/CoreFoundation.h>
+#include <mach/mach.h>
+#include <OpenGL/OpenGL.h>
+
+#include "base/basictypes.h"
+
+// This Mac OS X-specific class provides dynamically-linked access to
+// IOSurface.framework, which is only available on 10.6 and later.
+// Since Chromium is built on 10.5 we must dynamically look up all of
+// the entry points we need in this framework.
+
+// See IOSurface/IOSurfaceAPI.h and OpenGL/CGLIOSurface.h on 10.6 for
+// documentation of the fields and methods of this class.
+
+class IOSurfaceSupport {
+ public:
+ // Returns an instance of the IOSurfaceSupport class if the
+ // operating system supports it, NULL otherwise. It is safe to call
+ // this multiple times.
+ static IOSurfaceSupport* Initialize();
+
+ virtual CFStringRef GetKIOSurfaceWidth() = 0;
+ virtual CFStringRef GetKIOSurfaceHeight() = 0;
+ virtual CFStringRef GetKIOSurfaceBytesPerElement() = 0;
+ virtual CFStringRef GetKIOSurfaceIsGlobal() = 0;
+
+ virtual CFTypeRef IOSurfaceCreate(CFDictionaryRef properties) = 0;
+
+ // The following two APIs assume the IOSurface was created with the
+ // kIOSurfaceIsGlobal key set to true
+ virtual uint32 IOSurfaceGetID(CFTypeRef io_surface) = 0;
+ virtual CFTypeRef IOSurfaceLookup(uint32 io_surface_id) = 0;
+
+ // The following two APIs are more robust and secure, but
+ // unfortunately it looks like it will be a lot of work to correctly
+ // transmit a mach port from process to process (possibly requiring
+ // a side channel for or extension of the Chrome IPC mechanism)
+ virtual mach_port_t IOSurfaceCreateMachPort(CFTypeRef io_surface) = 0;
+ virtual CFTypeRef IOSurfaceLookupFromMachPort(mach_port_t port) = 0;
+
+ virtual CGLError CGLTexImageIOSurface2D(CGLContextObj ctx,
+ GLenum target,
+ GLenum internal_format,
+ GLsizei width,
+ GLsizei height,
+ GLenum format,
+ GLenum type,
+ CFTypeRef io_surface,
+ GLuint plane) = 0;
+
+ protected:
+ IOSurfaceSupport();
+ virtual ~IOSurfaceSupport();
+
+ DISALLOW_COPY_AND_ASSIGN(IOSurfaceSupport);
+};
+
+#endif // APP_SURFACE_IO_SURFACE_SUPPORT_MAC_H_
+
diff --git a/app/surface/transport_dib.h b/app/surface/transport_dib.h
new file mode 100644
index 0000000..7a60f08
--- /dev/null
+++ b/app/surface/transport_dib.h
@@ -0,0 +1,156 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef APP_SURFACE_TRANSPORT_DIB_H_
+#define APP_SURFACE_TRANSPORT_DIB_H_
+
+#include "base/basictypes.h"
+
+#if defined(OS_WIN) || defined(OS_MACOSX)
+#include "base/shared_memory.h"
+#endif
+
+#if defined(OS_WIN)
+#include <windows.h>
+#elif defined(USE_X11)
+#include "app/x11_util.h"
+#endif
+
+namespace gfx {
+class Size;
+}
+namespace skia {
+class PlatformCanvas;
+}
+
+// -----------------------------------------------------------------------------
+// A TransportDIB is a block of memory that is used to transport pixels
+// between processes: from the renderer process to the browser, and
+// between renderer and plugin processes.
+// -----------------------------------------------------------------------------
+class TransportDIB {
+ public:
+ ~TransportDIB();
+
+ // Two typedefs are defined. A Handle is the type which can be sent over
+ // the wire so that the remote side can map the transport DIB. The Id typedef
+ // is sufficient to identify the transport DIB when you know that the remote
+ // side already may have it mapped.
+#if defined(OS_WIN)
+ typedef HANDLE Handle;
+ // On Windows, the Id type includes a sequence number (epoch) to solve an ABA
+ // issue:
+ // 1) Process A creates a transport DIB with HANDLE=1 and sends to B.
+ // 2) Process B maps the transport DIB and caches 1 -> DIB.
+ // 3) Process A closes the transport DIB and creates a new one. The new DIB
+ // is also assigned HANDLE=1.
+ // 4) Process A sends the Handle to B, but B incorrectly believes that it
+ // already has it cached.
+ struct HandleAndSequenceNum {
+ HandleAndSequenceNum()
+ : handle(NULL),
+ sequence_num(0) {
+ }
+
+ HandleAndSequenceNum(HANDLE h, uint32 seq_num)
+ : handle(h),
+ sequence_num(seq_num) {
+ }
+
+ bool operator< (const HandleAndSequenceNum& other) const {
+ // Use the lexicographic order on the tuple <handle, sequence_num>.
+ if (other.handle != handle)
+ return other.handle < handle;
+ return other.sequence_num < sequence_num;
+ }
+
+ HANDLE handle;
+ uint32 sequence_num;
+ };
+ typedef HandleAndSequenceNum Id;
+
+ // Returns a default, invalid handle, that is meant to indicate a missing
+ // Transport DIB.
+ static Handle DefaultHandleValue() { return NULL; }
+#elif defined(OS_MACOSX)
+ typedef base::SharedMemoryHandle Handle;
+ // On Mac, the inode number of the backing file is used as an id.
+ typedef base::SharedMemoryId Id;
+
+ // Returns a default, invalid handle, that is meant to indicate a missing
+ // Transport DIB.
+ static Handle DefaultHandleValue() { return Handle(); }
+#elif defined(USE_X11)
+ typedef int Handle; // These two ints are SysV IPC shared memory keys
+ typedef int Id;
+
+ // Returns a default, invalid handle, that is meant to indicate a missing
+ // Transport DIB.
+ static Handle DefaultHandleValue() { return -1; }
+#endif
+
+ // Create a new TransportDIB, returning NULL on failure.
+ //
+ // The size is the minimum size in bytes of the memory backing the transport
+ // DIB (we may actually allocate more than that to give us better reuse when
+ // cached).
+ //
+ // The sequence number is used to uniquely identify the transport DIB. It
+ // should be unique for all transport DIBs ever created in the same
+ // renderer.
+ static TransportDIB* Create(size_t size, uint32 sequence_num);
+
+ // Map the referenced transport DIB. Returns NULL on failure.
+ static TransportDIB* Map(Handle transport_dib);
+
+ // Returns true if the handle is valid.
+ static bool is_valid(Handle dib);
+
+ // Returns a canvas using the memory of this TransportDIB. The returned
+ // pointer will be owned by the caller. The bitmap will be of the given size,
+ // which should fit inside this memory.
+ skia::PlatformCanvas* GetPlatformCanvas(int w, int h);
+
+ // Return a pointer to the shared memory
+ void* memory() const;
+
+ // Return the maximum size of the shared memory. This is not the amount of
+ // data which is valid, you have to know that via other means, this is simply
+ // the maximum amount that /could/ be valid.
+ size_t size() const { return size_; }
+
+ // Return the identifier which can be used to refer to this shared memory
+ // on the wire.
+ Id id() const;
+
+ // Return a handle to the underlying shared memory. This can be sent over the
+ // wire to give this transport DIB to another process.
+ Handle handle() const;
+
+#if defined(USE_X11)
+ // Map the shared memory into the X server and return an id for the shared
+ // segment.
+ XID MapToX(Display* connection);
+#endif
+
+ private:
+ TransportDIB();
+#if defined(OS_WIN) || defined(OS_MACOSX)
+ explicit TransportDIB(base::SharedMemoryHandle dib);
+ base::SharedMemory shared_memory_;
+ uint32 sequence_num_;
+#elif defined(USE_X11)
+ int key_; // SysV shared memory id
+ void* address_; // mapped address
+ XSharedMemoryId x_shm_; // X id for the shared segment
+ Display* display_; // connection to the X server
+#endif
+ size_t size_; // length, in bytes
+
+ DISALLOW_COPY_AND_ASSIGN(TransportDIB);
+};
+
+class MessageLoop;
+
+#endif // APP_SURFACE_TRANSPORT_DIB_H_
diff --git a/app/surface/transport_dib_linux.cc b/app/surface/transport_dib_linux.cc
new file mode 100644
index 0000000..6c41a0c
--- /dev/null
+++ b/app/surface/transport_dib_linux.cc
@@ -0,0 +1,113 @@
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <errno.h>
+#include <stdlib.h>
+#include <sys/ipc.h>
+#include <sys/shm.h>
+
+#include "app/surface/transport_dib.h"
+#include "app/x11_util.h"
+#include "base/logging.h"
+#include "gfx/size.h"
+#include "skia/ext/platform_canvas.h"
+
+// The shmat system call uses this as it's invalid return address
+static void *const kInvalidAddress = (void*) -1;
+
+TransportDIB::TransportDIB()
+ : key_(-1),
+ address_(kInvalidAddress),
+ x_shm_(0),
+ display_(NULL),
+ size_(0) {
+}
+
+TransportDIB::~TransportDIB() {
+ if (address_ != kInvalidAddress) {
+ shmdt(address_);
+ address_ = kInvalidAddress;
+ }
+
+ if (x_shm_) {
+ DCHECK(display_);
+ x11_util::DetachSharedMemory(display_, x_shm_);
+ }
+}
+
+// static
+TransportDIB* TransportDIB::Create(size_t size, uint32 sequence_num) {
+ // We use a mode of 0666 since the X server won't attach to memory which is
+ // 0600 since it can't know if it (as a root process) is being asked to map
+ // someone else's private shared memory region.
+ const int shmkey = shmget(IPC_PRIVATE, size, 0666);
+ if (shmkey == -1) {
+ DLOG(ERROR) << "Failed to create SysV shared memory region"
+ << " errno:" << errno;
+ return NULL;
+ }
+
+ void* address = shmat(shmkey, NULL /* desired address */, 0 /* flags */);
+ // Here we mark the shared memory for deletion. Since we attached it in the
+ // line above, it doesn't actually get deleted but, if we crash, this means
+ // that the kernel will automatically clean it up for us.
+ shmctl(shmkey, IPC_RMID, 0);
+ if (address == kInvalidAddress)
+ return NULL;
+
+ TransportDIB* dib = new TransportDIB;
+
+ dib->key_ = shmkey;
+ dib->address_ = address;
+ dib->size_ = size;
+ return dib;
+}
+
+TransportDIB* TransportDIB::Map(Handle shmkey) {
+ struct shmid_ds shmst;
+ if (shmctl(shmkey, IPC_STAT, &shmst) == -1)
+ return NULL;
+
+ void* address = shmat(shmkey, NULL /* desired address */, 0 /* flags */);
+ if (address == kInvalidAddress)
+ return NULL;
+
+ TransportDIB* dib = new TransportDIB;
+
+ dib->address_ = address;
+ dib->size_ = shmst.shm_segsz;
+ dib->key_ = shmkey;
+ return dib;
+}
+
+bool TransportDIB::is_valid(Handle dib) {
+ return dib >= 0;
+}
+
+skia::PlatformCanvas* TransportDIB::GetPlatformCanvas(int w, int h) {
+ return new skia::PlatformCanvas(w, h, true,
+ reinterpret_cast<uint8_t*>(memory()));
+}
+
+void* TransportDIB::memory() const {
+ DCHECK_NE(address_, kInvalidAddress);
+ return address_;
+}
+
+TransportDIB::Id TransportDIB::id() const {
+ return key_;
+}
+
+TransportDIB::Handle TransportDIB::handle() const {
+ return key_;
+}
+
+XID TransportDIB::MapToX(Display* display) {
+ if (!x_shm_) {
+ x_shm_ = x11_util::AttachSharedMemory(display, key_);
+ display_ = display;
+ }
+
+ return x_shm_;
+}
diff --git a/app/surface/transport_dib_mac.cc b/app/surface/transport_dib_mac.cc
new file mode 100644
index 0000000..cc56ab6
--- /dev/null
+++ b/app/surface/transport_dib_mac.cc
@@ -0,0 +1,77 @@
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "app/surface/transport_dib.h"
+
+#include <unistd.h>
+#include <sys/stat.h>
+
+#include "base/eintr_wrapper.h"
+#include "base/shared_memory.h"
+#include "skia/ext/platform_canvas.h"
+
+TransportDIB::TransportDIB()
+ : size_(0) {
+}
+
+TransportDIB::TransportDIB(TransportDIB::Handle dib)
+ : shared_memory_(dib, false /* read write */),
+ size_(0) {
+}
+
+TransportDIB::~TransportDIB() {
+}
+
+// static
+TransportDIB* TransportDIB::Create(size_t size, uint32 sequence_num) {
+ TransportDIB* dib = new TransportDIB;
+ if (!dib->shared_memory_.Create(L"", false /* read write */,
+ false /* do not open existing */, size)) {
+ delete dib;
+ return NULL;
+ }
+
+ dib->size_ = size;
+ return dib;
+}
+
+// static
+TransportDIB* TransportDIB::Map(TransportDIB::Handle handle) {
+ if (!is_valid(handle))
+ return NULL;
+
+ TransportDIB* dib = new TransportDIB(handle);
+ struct stat st;
+ if ((fstat(handle.fd, &st) != 0) ||
+ (!dib->shared_memory_.Map(st.st_size))) {
+ delete dib;
+ HANDLE_EINTR(close(handle.fd));
+ return NULL;
+ }
+
+ dib->size_ = st.st_size;
+
+ return dib;
+}
+
+bool TransportDIB::is_valid(Handle dib) {
+ return dib.fd >= 0;
+}
+
+skia::PlatformCanvas* TransportDIB::GetPlatformCanvas(int w, int h) {
+ return new skia::PlatformCanvas(w, h, true,
+ reinterpret_cast<uint8_t*>(memory()));
+}
+
+void* TransportDIB::memory() const {
+ return shared_memory_.memory();
+}
+
+TransportDIB::Id TransportDIB::id() const {
+ return shared_memory_.id();
+}
+
+TransportDIB::Handle TransportDIB::handle() const {
+ return shared_memory_.handle();
+}
diff --git a/app/surface/transport_dib_win.cc b/app/surface/transport_dib_win.cc
new file mode 100644
index 0000000..2a92fb1
--- /dev/null
+++ b/app/surface/transport_dib_win.cc
@@ -0,0 +1,81 @@
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <limits>
+#include <windows.h>
+
+#include "app/surface/transport_dib.h"
+#include "base/logging.h"
+#include "base/sys_info.h"
+#include "skia/ext/platform_canvas.h"
+
+TransportDIB::TransportDIB() {
+}
+
+TransportDIB::~TransportDIB() {
+}
+
+TransportDIB::TransportDIB(HANDLE handle)
+ : shared_memory_(handle, false /* read write */) {
+}
+
+// static
+TransportDIB* TransportDIB::Create(size_t size, uint32 sequence_num) {
+ size_t allocation_granularity = base::SysInfo::VMAllocationGranularity();
+ size = size / allocation_granularity + 1;
+ size = size * allocation_granularity;
+
+ TransportDIB* dib = new TransportDIB;
+
+ if (!dib->shared_memory_.Create(L"", false /* read write */,
+ true /* open existing */, size)) {
+ delete dib;
+ return NULL;
+ }
+
+ dib->size_ = size;
+ dib->sequence_num_ = sequence_num;
+
+ return dib;
+}
+
+// static
+TransportDIB* TransportDIB::Map(TransportDIB::Handle handle) {
+ TransportDIB* dib = new TransportDIB(handle);
+ if (!dib->shared_memory_.Map(0 /* map whole shared memory segment */)) {
+ LOG(ERROR) << "Failed to map transport DIB"
+ << " handle:" << handle
+ << " error:" << GetLastError();
+ delete dib;
+ return NULL;
+ }
+
+ // There doesn't seem to be any way to find the size of the shared memory
+ // region! GetFileSize indicates that the handle is invalid. Thus, we
+ // conservatively set the size to the maximum and hope that the renderer
+ // isn't about to ask us to read off the end of the array.
+ dib->size_ = std::numeric_limits<size_t>::max();
+
+ return dib;
+}
+
+bool TransportDIB::is_valid(Handle dib) {
+ return dib != NULL;
+}
+
+skia::PlatformCanvas* TransportDIB::GetPlatformCanvas(int w, int h) {
+ return new skia::PlatformCanvas(w, h, true, handle());
+}
+
+void* TransportDIB::memory() const {
+ return shared_memory_.memory();
+}
+
+TransportDIB::Handle TransportDIB::handle() const {
+ return shared_memory_.handle();
+}
+
+TransportDIB::Id TransportDIB::id() const {
+ return Id(shared_memory_.handle(), sequence_num_);
+}
diff --git a/app/x11_util.cc b/app/x11_util.cc
new file mode 100644
index 0000000..38799ad
--- /dev/null
+++ b/app/x11_util.cc
@@ -0,0 +1,751 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// This file defines utility functions for X11 (Linux only). This code has been
+// ported from XCB since we can't use XCB on Ubuntu while its 32-bit support
+// remains woefully incomplete.
+
+#include "app/x11_util.h"
+
+#include <gdk/gdk.h>
+#include <gdk/gdkx.h>
+#include <gtk/gtk.h>
+
+#include <sys/ipc.h>
+#include <sys/shm.h>
+
+#include <list>
+#include <set>
+
+#include "base/command_line.h"
+#include "base/logging.h"
+#include "base/thread.h"
+#include "app/x11_util_internal.h"
+#include "gfx/size.h"
+
+namespace x11_util {
+
+namespace {
+
+// Used to cache the XRenderPictFormat for a visual/display pair.
+struct CachedPictFormat {
+ bool equals(Display* display, Visual* visual) const {
+ return display == this->display && visual == this->visual;
+ }
+
+ Display* display;
+ Visual* visual;
+ XRenderPictFormat* format;
+};
+
+typedef std::list<CachedPictFormat> CachedPictFormats;
+
+// Returns the cache of pict formats.
+CachedPictFormats* get_cached_pict_formats() {
+ static CachedPictFormats* formats = NULL;
+ if (!formats)
+ formats = new CachedPictFormats();
+ return formats;
+}
+
+// Maximum number of CachedPictFormats we keep around.
+const size_t kMaxCacheSize = 5;
+
+} // namespace
+
+bool XDisplayExists() {
+ return (gdk_display_get_default() != NULL);
+}
+
+Display* GetXDisplay() {
+ static Display* display = NULL;
+
+ if (!display)
+ display = gdk_x11_get_default_xdisplay();
+
+ return display;
+}
+
+static SharedMemorySupport DoQuerySharedMemorySupport(Display* dpy) {
+ // A temporary flag for tracking down shared memory problems.
+ // TODO(evanm): remove this.
+ if (CommandLine::ForCurrentProcess()->HasSwitch("disable-xshm"))
+ return SHARED_MEMORY_NONE;
+
+ int dummy;
+ Bool pixmaps_supported;
+ // Query the server's support for XSHM.
+ if (!XShmQueryVersion(dpy, &dummy, &dummy, &pixmaps_supported))
+ return SHARED_MEMORY_NONE;
+
+ // Next we probe to see if shared memory will really work
+ int shmkey = shmget(IPC_PRIVATE, 1, 0666);
+ if (shmkey == -1)
+ return SHARED_MEMORY_NONE;
+ void* address = shmat(shmkey, NULL, 0);
+ // Mark the shared memory region for deletion
+ shmctl(shmkey, IPC_RMID, NULL);
+
+ XShmSegmentInfo shminfo;
+ memset(&shminfo, 0, sizeof(shminfo));
+ shminfo.shmid = shmkey;
+
+ gdk_error_trap_push();
+ bool result = XShmAttach(dpy, &shminfo);
+ XSync(dpy, False);
+ if (gdk_error_trap_pop())
+ result = false;
+ shmdt(address);
+ if (!result)
+ return SHARED_MEMORY_NONE;
+
+ XShmDetach(dpy, &shminfo);
+ return pixmaps_supported ? SHARED_MEMORY_PIXMAP : SHARED_MEMORY_PUTIMAGE;
+}
+
+SharedMemorySupport QuerySharedMemorySupport(Display* dpy) {
+ static SharedMemorySupport shared_memory_support = SHARED_MEMORY_NONE;
+ static bool shared_memory_support_cached = false;
+
+ if (shared_memory_support_cached)
+ return shared_memory_support;
+
+ shared_memory_support = DoQuerySharedMemorySupport(dpy);
+ shared_memory_support_cached = true;
+
+ return shared_memory_support;
+}
+
+bool QueryRenderSupport(Display* dpy) {
+ static bool render_supported = false;
+ static bool render_supported_cached = false;
+
+ if (render_supported_cached)
+ return render_supported;
+
+ // We don't care about the version of Xrender since all the features which
+ // we use are included in every version.
+ int dummy;
+ render_supported = XRenderQueryExtension(dpy, &dummy, &dummy);
+ render_supported_cached = true;
+
+ return render_supported;
+}
+
+int GetDefaultScreen(Display* display) {
+ return XDefaultScreen(display);
+}
+
+XID GetX11RootWindow() {
+ return GDK_WINDOW_XID(gdk_get_default_root_window());
+}
+
+XID GetX11WindowFromGtkWidget(GtkWidget* widget) {
+ return GDK_WINDOW_XID(widget->window);
+}
+
+XID GetX11WindowFromGdkWindow(GdkWindow* window) {
+ return GDK_WINDOW_XID(window);
+}
+
+void* GetVisualFromGtkWidget(GtkWidget* widget) {
+ return GDK_VISUAL_XVISUAL(gtk_widget_get_visual(widget));
+}
+
+int BitsPerPixelForPixmapDepth(Display* dpy, int depth) {
+ int count;
+ XPixmapFormatValues* formats = XListPixmapFormats(dpy, &count);
+ if (!formats)
+ return -1;
+
+ int bits_per_pixel = -1;
+ for (int i = 0; i < count; ++i) {
+ if (formats[i].depth == depth) {
+ bits_per_pixel = formats[i].bits_per_pixel;
+ break;
+ }
+ }
+
+ XFree(formats);
+ return bits_per_pixel;
+}
+
+bool IsWindowVisible(XID window) {
+ XWindowAttributes win_attributes;
+ XGetWindowAttributes(GetXDisplay(), window, &win_attributes);
+ return (win_attributes.map_state == IsViewable);
+}
+
+bool GetWindowRect(XID window, gfx::Rect* rect) {
+ Window root, child;
+ int x, y;
+ unsigned int width, height;
+ unsigned int border_width, depth;
+
+ if (!XGetGeometry(GetXDisplay(), window, &root, &x, &y,
+ &width, &height, &border_width, &depth))
+ return false;
+
+ if (!XTranslateCoordinates(GetSecondaryDisplay(), window, root,
+ 0, 0, &x, &y, &child))
+ return false;
+
+ *rect = gfx::Rect(x, y, width, height);
+ return true;
+}
+
+bool GetIntProperty(XID window, const std::string& property_name, int* value) {
+ Atom property_atom = gdk_x11_get_xatom_by_name_for_display(
+ gdk_display_get_default(), property_name.c_str());
+
+ Atom type = None;
+ int format = 0; // size in bits of each item in 'property'
+ long unsigned int num_items = 0, remaining_bytes = 0;
+ unsigned char* property = NULL;
+
+ int result = XGetWindowProperty(GetXDisplay(),
+ window,
+ property_atom,
+ 0, // offset into property data to read
+ 1, // max length to get
+ False, // deleted
+ AnyPropertyType,
+ &type,
+ &format,
+ &num_items,
+ &remaining_bytes,
+ &property);
+ if (result != Success)
+ return false;
+
+ if (format != 32 || num_items != 1) {
+ XFree(property);
+ return false;
+ }
+
+ *value = *(reinterpret_cast<int*>(property));
+ XFree(property);
+ return true;
+}
+
+bool GetStringProperty(
+ XID window, const std::string& property_name, std::string* value) {
+ Atom property_atom = gdk_x11_get_xatom_by_name_for_display(
+ gdk_display_get_default(), property_name.c_str());
+
+ Atom type = None;
+ int format = 0; // size in bits of each item in 'property'
+ long unsigned int num_items = 0, remaining_bytes = 0;
+ unsigned char* property = NULL;
+
+ int result = XGetWindowProperty(GetXDisplay(),
+ window,
+ property_atom,
+ 0, // offset into property data to read
+ 1024, // max length to get
+ False, // deleted
+ AnyPropertyType,
+ &type,
+ &format,
+ &num_items,
+ &remaining_bytes,
+ &property);
+ if (result != Success)
+ return false;
+
+ if (format != 8) {
+ XFree(property);
+ return false;
+ }
+
+ value->assign(reinterpret_cast<char*>(property), num_items);
+ XFree(property);
+ return true;
+}
+
+XID GetParentWindow(XID window) {
+ XID root = None;
+ XID parent = None;
+ XID* children = NULL;
+ unsigned int num_children = 0;
+ XQueryTree(GetXDisplay(), window, &root, &parent, &children, &num_children);
+ if (children)
+ XFree(children);
+ return parent;
+}
+
+XID GetHighestAncestorWindow(XID window, XID root) {
+ while (true) {
+ XID parent = x11_util::GetParentWindow(window);
+ if (parent == None)
+ return None;
+ if (parent == root)
+ return window;
+ window = parent;
+ }
+}
+
+// Returns true if |window| is a named window.
+bool IsWindowNamed(XID window) {
+ XTextProperty prop;
+ if (!XGetWMName(GetXDisplay(), window, &prop) || !prop.value)
+ return false;
+
+ XFree(prop.value);
+ return true;
+}
+
+bool EnumerateChildren(EnumerateWindowsDelegate* delegate, XID window,
+ const int max_depth, int depth) {
+ if (depth > max_depth)
+ return false;
+
+ XID root, parent, *children;
+ unsigned int num_children;
+ int status = XQueryTree(GetXDisplay(), window, &root, &parent, &children,
+ &num_children);
+ if (status == 0)
+ return false;
+
+ std::set<XID> windows;
+ for (unsigned int i = 0; i < num_children; i++)
+ windows.insert(children[i]);
+
+ XFree(children);
+
+ // XQueryTree returns the children of |window| in bottom-to-top order, so
+ // reverse-iterate the list to check the windows from top-to-bottom.
+ std::set<XID>::reverse_iterator iter;
+ for (iter = windows.rbegin(); iter != windows.rend(); iter++) {
+ if (IsWindowNamed(*iter) && delegate->ShouldStopIterating(*iter))
+ return true;
+ }
+
+ // If we're at this point, we didn't find the window we're looking for at the
+ // current level, so we need to recurse to the next level. We use a second
+ // loop because the recursion and call to XQueryTree are expensive and is only
+ // needed for a small number of cases.
+ if (++depth <= max_depth) {
+ for (iter = windows.rbegin(); iter != windows.rend(); iter++) {
+ if (EnumerateChildren(delegate, *iter, max_depth, depth))
+ return true;
+ }
+ }
+
+ return false;
+}
+
+bool EnumerateAllWindows(EnumerateWindowsDelegate* delegate, int max_depth) {
+ XID root = GetX11RootWindow();
+ return EnumerateChildren(delegate, root, max_depth, 0);
+}
+
+bool GetXWindowStack(std::vector<XID>* windows) {
+ windows->clear();
+
+ static Atom atom = XInternAtom(GetXDisplay(),
+ "_NET_CLIENT_LIST_STACKING", False);
+
+ Atom type;
+ int format;
+ unsigned long count;
+ unsigned long bytes_after;
+ unsigned char *data = NULL;
+ if (XGetWindowProperty(GetXDisplay(),
+ GetX11RootWindow(),
+ atom,
+ 0, // offset
+ ~0L, // length
+ False, // delete
+ AnyPropertyType, // requested type
+ &type,
+ &format,
+ &count,
+ &bytes_after,
+ &data) != Success) {
+ return false;
+ }
+
+ bool result = false;
+ if (type == XA_WINDOW && format == 32 && data && count > 0) {
+ result = true;
+ XID* stack = reinterpret_cast<XID*>(data);
+ for (unsigned long i = 0; i < count; i++)
+ windows->insert(windows->begin(), stack[i]);
+ }
+
+ if (data)
+ XFree(data);
+
+ return result;
+}
+
+void RestackWindow(XID window, XID sibling, bool above) {
+ XWindowChanges changes;
+ changes.sibling = sibling;
+ changes.stack_mode = above ? Above : Below;
+ XConfigureWindow(GetXDisplay(), window, CWSibling | CWStackMode, &changes);
+}
+
+XRenderPictFormat* GetRenderVisualFormat(Display* dpy, Visual* visual) {
+ DCHECK(QueryRenderSupport(dpy));
+
+ CachedPictFormats* formats = get_cached_pict_formats();
+
+ for (CachedPictFormats::const_iterator i = formats->begin();
+ i != formats->end(); ++i) {
+ if (i->equals(dpy, visual))
+ return i->format;
+ }
+
+ // Not cached, look up the value.
+ XRenderPictFormat* pictformat = XRenderFindVisualFormat(dpy, visual);
+ CHECK(pictformat) << "XRENDER does not support default visual";
+
+ // And store it in the cache.
+ CachedPictFormat cached_value;
+ cached_value.visual = visual;
+ cached_value.display = dpy;
+ cached_value.format = pictformat;
+ formats->push_front(cached_value);
+
+ if (formats->size() == kMaxCacheSize) {
+ formats->pop_back();
+ // We should really only have at most 2 display/visual combinations:
+ // one for normal browser windows, and possibly another for an argb window
+ // created to display a menu.
+ //
+ // If we get here it's not fatal, we just need to make sure we aren't
+ // always blowing away the cache. If we are, then we should figure out why
+ // and make it bigger.
+ NOTREACHED();
+ }
+
+ return pictformat;
+}
+
+XRenderPictFormat* GetRenderARGB32Format(Display* dpy) {
+ static XRenderPictFormat* pictformat = NULL;
+ if (pictformat)
+ return pictformat;
+
+ // First look for a 32-bit format which ignores the alpha value
+ XRenderPictFormat templ;
+ templ.depth = 32;
+ templ.type = PictTypeDirect;
+ templ.direct.red = 16;
+ templ.direct.green = 8;
+ templ.direct.blue = 0;
+ templ.direct.redMask = 0xff;
+ templ.direct.greenMask = 0xff;
+ templ.direct.blueMask = 0xff;
+ templ.direct.alphaMask = 0;
+
+ static const unsigned long kMask =
+ PictFormatType | PictFormatDepth |
+ PictFormatRed | PictFormatRedMask |
+ PictFormatGreen | PictFormatGreenMask |
+ PictFormatBlue | PictFormatBlueMask |
+ PictFormatAlphaMask;
+
+ pictformat = XRenderFindFormat(dpy, kMask, &templ, 0 /* first result */);
+
+ if (!pictformat) {
+ // Not all X servers support xRGB32 formats. However, the XRENDER spec says
+ // that they must support an ARGB32 format, so we can always return that.
+ pictformat = XRenderFindStandardFormat(dpy, PictStandardARGB32);
+ CHECK(pictformat) << "XRENDER ARGB32 not supported.";
+ }
+
+ return pictformat;
+}
+
+XSharedMemoryId AttachSharedMemory(Display* display, int shared_memory_key) {
+ DCHECK(QuerySharedMemorySupport(display));
+
+ XShmSegmentInfo shminfo;
+ memset(&shminfo, 0, sizeof(shminfo));
+ shminfo.shmid = shared_memory_key;
+
+ // This function is only called if QuerySharedMemorySupport returned true. In
+ // which case we've already succeeded in having the X server attach to one of
+ // our shared memory segments.
+ if (!XShmAttach(display, &shminfo))
+ NOTREACHED();
+
+ return shminfo.shmseg;
+}
+
+void DetachSharedMemory(Display* display, XSharedMemoryId shmseg) {
+ DCHECK(QuerySharedMemorySupport(display));
+
+ XShmSegmentInfo shminfo;
+ memset(&shminfo, 0, sizeof(shminfo));
+ shminfo.shmseg = shmseg;
+
+ if (!XShmDetach(display, &shminfo))
+ NOTREACHED();
+}
+
+XID CreatePictureFromSkiaPixmap(Display* display, XID pixmap) {
+ XID picture = XRenderCreatePicture(
+ display, pixmap, GetRenderARGB32Format(display), 0, NULL);
+
+ return picture;
+}
+
+void PutARGBImage(Display* display, void* visual, int depth, XID pixmap,
+ void* pixmap_gc, const uint8* data, int width, int height) {
+ // TODO(scherkus): potential performance impact... consider passing in as a
+ // parameter.
+ int pixmap_bpp = BitsPerPixelForPixmapDepth(display, depth);
+
+ XImage image;
+ memset(&image, 0, sizeof(image));
+
+ image.width = width;
+ image.height = height;
+ image.format = ZPixmap;
+ image.byte_order = LSBFirst;
+ image.bitmap_unit = 8;
+ image.bitmap_bit_order = LSBFirst;
+ image.depth = depth;
+ image.bits_per_pixel = pixmap_bpp;
+ image.bytes_per_line = width * pixmap_bpp / 8;
+
+ if (pixmap_bpp == 32) {
+ image.red_mask = 0xff0000;
+ image.green_mask = 0xff00;
+ image.blue_mask = 0xff;
+
+ // If the X server depth is already 32-bits and the color masks match,
+ // then our job is easy.
+ Visual* vis = static_cast<Visual*>(visual);
+ if (image.red_mask == vis->red_mask &&
+ image.green_mask == vis->green_mask &&
+ image.blue_mask == vis->blue_mask) {
+ image.data = const_cast<char*>(reinterpret_cast<const char*>(data));
+ XPutImage(display, pixmap, static_cast<GC>(pixmap_gc), &image,
+ 0, 0 /* source x, y */, 0, 0 /* dest x, y */,
+ width, height);
+ } else {
+ // Otherwise, we need to shuffle the colors around. Assume red and blue
+ // need to be swapped.
+ //
+ // It's possible to use some fancy SSE tricks here, but since this is the
+ // slow path anyway, we do it slowly.
+
+ uint8_t* bitmap32 = static_cast<uint8_t*>(malloc(4 * width * height));
+ if (!bitmap32)
+ return;
+ uint8_t* const orig_bitmap32 = bitmap32;
+ const uint32_t* bitmap_in = reinterpret_cast<const uint32_t*>(data);
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x) {
+ const uint32_t pixel = *(bitmap_in++);
+ bitmap32[0] = (pixel >> 16) & 0xff; // Red
+ bitmap32[1] = (pixel >> 8) & 0xff; // Green
+ bitmap32[2] = pixel & 0xff; // Blue
+ bitmap32[3] = (pixel >> 24) & 0xff; // Alpha
+ bitmap32 += 4;
+ }
+ }
+ image.data = reinterpret_cast<char*>(orig_bitmap32);
+ XPutImage(display, pixmap, static_cast<GC>(pixmap_gc), &image,
+ 0, 0 /* source x, y */, 0, 0 /* dest x, y */,
+ width, height);
+ free(orig_bitmap32);
+ }
+ } else if (pixmap_bpp == 16) {
+ // Some folks have VNC setups which still use 16-bit visuals and VNC
+ // doesn't include Xrender.
+
+ uint16_t* bitmap16 = static_cast<uint16_t*>(malloc(2 * width * height));
+ if (!bitmap16)
+ return;
+ uint16_t* const orig_bitmap16 = bitmap16;
+ const uint32_t* bitmap_in = reinterpret_cast<const uint32_t*>(data);
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x) {
+ const uint32_t pixel = *(bitmap_in++);
+ uint16_t out_pixel = ((pixel >> 8) & 0xf800) |
+ ((pixel >> 5) & 0x07e0) |
+ ((pixel >> 3) & 0x001f);
+ *(bitmap16++) = out_pixel;
+ }
+ }
+
+ image.data = reinterpret_cast<char*>(orig_bitmap16);
+ image.red_mask = 0xf800;
+ image.green_mask = 0x07e0;
+ image.blue_mask = 0x001f;
+
+ XPutImage(display, pixmap, static_cast<GC>(pixmap_gc), &image,
+ 0, 0 /* source x, y */, 0, 0 /* dest x, y */,
+ width, height);
+ free(orig_bitmap16);
+ } else {
+ CHECK(false) << "Sorry, we don't support your visual depth without "
+ "Xrender support (depth:" << depth
+ << " bpp:" << pixmap_bpp << ")";
+ }
+}
+
+void FreePicture(Display* display, XID picture) {
+ XRenderFreePicture(display, picture);
+}
+
+void FreePixmap(Display* display, XID pixmap) {
+ XFreePixmap(display, pixmap);
+}
+
+// Called on BACKGROUND_X11 thread.
+Display* GetSecondaryDisplay() {
+ static Display* display = NULL;
+ if (!display) {
+ display = XOpenDisplay(NULL);
+ CHECK(display);
+ }
+
+ return display;
+}
+
+// Called on BACKGROUND_X11 thread.
+bool GetWindowGeometry(int* x, int* y, unsigned* width, unsigned* height,
+ XID window) {
+ Window root_window, child_window;
+ unsigned border_width, depth;
+ int temp;
+
+ if (!XGetGeometry(GetSecondaryDisplay(), window, &root_window, &temp, &temp,
+ width, height, &border_width, &depth))
+ return false;
+ if (!XTranslateCoordinates(GetSecondaryDisplay(), window, root_window,
+ 0, 0 /* input x, y */, x, y /* output x, y */,
+ &child_window))
+ return false;
+
+ return true;
+}
+
+// Called on BACKGROUND_X11 thread.
+bool GetWindowParent(XID* parent_window, bool* parent_is_root, XID window) {
+ XID root_window, *children;
+ unsigned num_children;
+
+ Status s = XQueryTree(GetSecondaryDisplay(), window, &root_window,
+ parent_window, &children, &num_children);
+ if (!s)
+ return false;
+
+ if (children)
+ XFree(children);
+
+ *parent_is_root = root_window == *parent_window;
+ return true;
+}
+
+bool GetWindowManagerName(std::string* wm_name) {
+ DCHECK(wm_name);
+ int wm_window = 0;
+ if (!x11_util::GetIntProperty(x11_util::GetX11RootWindow(),
+ "_NET_SUPPORTING_WM_CHECK",
+ &wm_window)) {
+ return false;
+ }
+
+ // It's possible that a window manager started earlier in this X session left
+ // a stale _NET_SUPPORTING_WM_CHECK property when it was replaced by a
+ // non-EWMH window manager, so we trap errors in the following requests to
+ // avoid crashes (issue 23860).
+
+ // EWMH requires the supporting-WM window to also have a
+ // _NET_SUPPORTING_WM_CHECK property pointing to itself (to avoid a stale
+ // property referencing an ID that's been recycled for another window), so we
+ // check that too.
+ gdk_error_trap_push();
+ int wm_window_property = 0;
+ bool result = x11_util::GetIntProperty(
+ wm_window, "_NET_SUPPORTING_WM_CHECK", &wm_window_property);
+ gdk_flush();
+ bool got_error = gdk_error_trap_pop();
+ if (got_error || !result || wm_window_property != wm_window)
+ return false;
+
+ gdk_error_trap_push();
+ result = x11_util::GetStringProperty(
+ static_cast<XID>(wm_window), "_NET_WM_NAME", wm_name);
+ gdk_flush();
+ got_error = gdk_error_trap_pop();
+ return !got_error && result;
+}
+
+static cairo_status_t SnapshotCallback(
+ void *closure, const unsigned char *data, unsigned int length) {
+ std::vector<unsigned char>* png_representation =
+ static_cast<std::vector<unsigned char>*>(closure);
+
+ size_t old_size = png_representation->size();
+ png_representation->resize(old_size + length);
+ memcpy(&(*png_representation)[old_size], data, length);
+ return CAIRO_STATUS_SUCCESS;
+}
+
+void GrabWindowSnapshot(GtkWindow* gtk_window,
+ std::vector<unsigned char>* png_representation) {
+ GdkWindow* gdk_window = GTK_WIDGET(gtk_window)->window;
+ Display* display = GDK_WINDOW_XDISPLAY(gdk_window);
+ XID win = GDK_WINDOW_XID(gdk_window);
+ XWindowAttributes attr;
+ if (XGetWindowAttributes(display, win, &attr) != 0) {
+ LOG(ERROR) << "Couldn't get window attributes";
+ return;
+ }
+ XImage* image = XGetImage(
+ display, win, 0, 0, attr.width, attr.height, AllPlanes, ZPixmap);
+ if (!image) {
+ LOG(ERROR) << "Couldn't get image";
+ return;
+ }
+ if (image->depth != 24) {
+ LOG(ERROR)<< "Unsupported image depth " << image->depth;
+ return;
+ }
+ cairo_surface_t* surface =
+ cairo_image_surface_create_for_data(
+ reinterpret_cast<unsigned char*>(image->data),
+ CAIRO_FORMAT_RGB24,
+ image->width,
+ image->height,
+ image->bytes_per_line);
+
+ if (!surface) {
+ LOG(ERROR) << "Unable to create Cairo surface from XImage data";
+ return;
+ }
+ cairo_surface_write_to_png_stream(
+ surface, SnapshotCallback, png_representation);
+ cairo_surface_destroy(surface);
+}
+
+bool ChangeWindowDesktop(XID window, XID destination) {
+ int desktop;
+ if (!GetIntProperty(destination, "_NET_WM_DESKTOP", &desktop))
+ return false;
+
+ XEvent event;
+ event.xclient.type = ClientMessage;
+ event.xclient.window = window;
+ event.xclient.message_type = gdk_x11_get_xatom_by_name_for_display(
+ gdk_display_get_default(), "_NET_WM_DESKTOP");
+ event.xclient.format = 32;
+ event.xclient.data.l[0] = desktop;
+ event.xclient.data.l[1] = 1; // source indication
+
+ int result = XSendEvent(GetXDisplay(), GetX11RootWindow(), False,
+ SubstructureNotifyMask, &event);
+ return result == Success;
+}
+
+} // namespace x11_util
diff --git a/app/x11_util.h b/app/x11_util.h
new file mode 100644
index 0000000..1c8685f1
--- /dev/null
+++ b/app/x11_util.h
@@ -0,0 +1,173 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef APP_X11_UTIL_H_
+#define APP_X11_UTIL_H_
+
+// This file declares utility functions for X11 (Linux only).
+//
+// These functions do not require the Xlib headers to be included (which is why
+// we use a void* for Visual*). The Xlib headers are highly polluting so we try
+// hard to limit their spread into the rest of the code.
+
+#include <string>
+#include <vector>
+
+#include "base/task.h"
+#include "gfx/rect.h"
+
+typedef struct _GdkDrawable GdkWindow;
+typedef struct _GtkWidget GtkWidget;
+typedef struct _GtkWindow GtkWindow;
+typedef unsigned long XID;
+typedef unsigned long XSharedMemoryId; // ShmSeg in the X headers.
+typedef struct _XDisplay Display;
+
+namespace base {
+class Thread;
+}
+
+namespace gfx {
+class Size;
+}
+
+namespace x11_util {
+
+// These functions use the GDK default display and this /must/ be called from
+// the UI thread. Thus, they don't support multiple displays.
+
+// These functions cache their results ---------------------------------
+
+// Check if there's an open connection to an X server.
+bool XDisplayExists();
+// Return an X11 connection for the current, primary display.
+Display* GetXDisplay();
+
+// X shared memory comes in three flavors:
+// 1) No SHM support,
+// 2) SHM putimage,
+// 3) SHM pixmaps + putimage.
+enum SharedMemorySupport {
+ SHARED_MEMORY_NONE,
+ SHARED_MEMORY_PUTIMAGE,
+ SHARED_MEMORY_PIXMAP
+};
+// Return the shared memory type of our X connection.
+SharedMemorySupport QuerySharedMemorySupport(Display* dpy);
+
+// Return true iff the display supports Xrender
+bool QueryRenderSupport(Display* dpy);
+
+// Return the default screen number for the display
+int GetDefaultScreen(Display* display);
+
+// These functions do not cache their results --------------------------
+
+// Get the X window id for the default root window
+XID GetX11RootWindow();
+// Get the X window id for the given GTK widget.
+XID GetX11WindowFromGtkWidget(GtkWidget* widget);
+XID GetX11WindowFromGdkWindow(GdkWindow* window);
+// Get a Visual from the given widget. Since we don't include the Xlib
+// headers, this is returned as a void*.
+void* GetVisualFromGtkWidget(GtkWidget* widget);
+// Return the number of bits-per-pixel for a pixmap of the given depth
+int BitsPerPixelForPixmapDepth(Display* display, int depth);
+// Returns true if |window| is visible.
+bool IsWindowVisible(XID window);
+// Returns the bounds of |window|.
+bool GetWindowRect(XID window, gfx::Rect* rect);
+// Get the value of an int or string property. On success, true is returned and
+// the value is stored in |value|.
+bool GetIntProperty(XID window, const std::string& property_name, int* value);
+bool GetStringProperty(
+ XID window, const std::string& property_name, std::string* value);
+
+// Get |window|'s parent window, or None if |window| is the root window.
+XID GetParentWindow(XID window);
+
+// Walk up |window|'s hierarchy until we find a direct child of |root|.
+XID GetHighestAncestorWindow(XID window, XID root);
+
+// Implementers of this interface receive a notification for every X window of
+// the main display.
+class EnumerateWindowsDelegate {
+ public:
+ // |xid| is the X Window ID of the enumerated window. Return true to stop
+ // further iteration.
+ virtual bool ShouldStopIterating(XID xid) = 0;
+
+ protected:
+ virtual ~EnumerateWindowsDelegate() {}
+};
+
+// Enumerates all windows in the current display. Will recurse into child
+// windows up to a depth of |max_depth|.
+bool EnumerateAllWindows(EnumerateWindowsDelegate* delegate, int max_depth);
+
+// Returns a list of top-level windows in top-to-bottom stacking order.
+bool GetXWindowStack(std::vector<XID>* windows);
+
+// Restack a window in relation to one of its siblings. If |above| is true,
+// |window| will be stacked directly above |sibling|; otherwise it will stacked
+// directly below it. Both windows must be immediate children of the same
+// window.
+void RestackWindow(XID window, XID sibling, bool above);
+
+// Return a handle to a X ShmSeg. |shared_memory_key| is a SysV
+// IPC key. The shared memory region must contain 32-bit pixels.
+XSharedMemoryId AttachSharedMemory(Display* display, int shared_memory_support);
+void DetachSharedMemory(Display* display, XSharedMemoryId shmseg);
+
+// Return a handle to an XRender picture where |pixmap| is a handle to a
+// pixmap containing Skia ARGB data.
+XID CreatePictureFromSkiaPixmap(Display* display, XID pixmap);
+
+// Draws ARGB data on the given pixmap using the given GC, converting to the
+// server side visual depth as needed. Destination is assumed to be the same
+// dimensions as |data| or larger. |data| is also assumed to be in row order
+// with each line being exactly |width| * 4 bytes long.
+void PutARGBImage(Display* display, void* visual, int depth, XID pixmap,
+ void* pixmap_gc, const uint8* data, int width, int height);
+
+void FreePicture(Display* display, XID picture);
+void FreePixmap(Display* display, XID pixmap);
+
+// These functions are for performing X opertions outside of the UI thread.
+
+// Return the Display for the secondary X connection. We keep a second
+// connection around for making X requests outside of the UI thread.
+// This function may only be called from the BACKGROUND_X11 thread.
+Display* GetSecondaryDisplay();
+
+// Since one cannot include both WebKit header and Xlib headers in the same
+// file (due to collisions), we wrap all the Xlib functions that we need here.
+// These functions must be called on the BACKGROUND_X11 thread since they
+// reference GetSecondaryDisplay().
+
+// Get the position of the given window in screen coordinates as well as its
+// current size.
+bool GetWindowGeometry(int* x, int* y, unsigned* width, unsigned* height,
+ XID window);
+
+// Find the immediate parent of an X window.
+//
+// parent_window: (output) the parent window of |window|, or 0.
+// parent_is_root: (output) true iff the parent of |window| is the root window.
+bool GetWindowParent(XID* parent_window, bool* parent_is_root, XID window);
+
+// Get the window manager name.
+bool GetWindowManagerName(std::string* name);
+
+// Grabs a snapshot of the designated window and stores a PNG representation
+// into a byte vector.
+void GrabWindowSnapshot(GtkWindow* gdk_window,
+ std::vector<unsigned char>* png_representation);
+
+// Change desktop for |window| to the desktop of |destination| window.
+bool ChangeWindowDesktop(XID window, XID destination);
+
+} // namespace x11_util
+
+#endif // APP_X11_UTIL_H_
diff --git a/app/x11_util_internal.h b/app/x11_util_internal.h
new file mode 100644
index 0000000..81f2820
--- /dev/null
+++ b/app/x11_util_internal.h
@@ -0,0 +1,35 @@
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef APP_X11_UTIL_INTERNAL_H_
+#define APP_X11_UTIL_INTERNAL_H_
+
+// This file declares utility functions for X11 (Linux only).
+//
+// These functions require the inclusion of the Xlib headers. Since the Xlib
+// headers pollute so much of the namespace, this should only be included
+// when needed.
+
+extern "C" {
+#include <X11/Xatom.h>
+#include <X11/Xlib.h>
+#include <X11/extensions/XShm.h>
+#include <X11/extensions/Xrender.h>
+}
+
+namespace x11_util {
+ // NOTE: these function caches the results and must be called from the UI
+ // thread.
+
+ // Get the XRENDER format id for ARGB32 (Skia's format).
+ //
+ // NOTE:Currently this don't support multiple screens/displays.
+ XRenderPictFormat* GetRenderARGB32Format(Display* dpy);
+
+ // Get the XRENDER format id for the default visual on the first screen. This
+ // is the format which our GTK window will have.
+ XRenderPictFormat* GetRenderVisualFormat(Display* dpy, Visual* visual);
+};
+
+#endif // APP_X11_UTIL_INTERNAL_H_