1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "SharedDIBSurface.h"
8 
9 #include "cairo.h"
10 
11 namespace mozilla {
12 namespace gfx {
13 
14 static const cairo_user_data_key_t SHAREDDIB_KEY = {0};
15 
Create(HDC adc,uint32_t aWidth,uint32_t aHeight,bool aTransparent)16 bool SharedDIBSurface::Create(HDC adc, uint32_t aWidth, uint32_t aHeight,
17                               bool aTransparent) {
18   nsresult rv = mSharedDIB.Create(adc, aWidth, aHeight, aTransparent);
19   if (NS_FAILED(rv) || !mSharedDIB.IsValid()) return false;
20 
21   InitSurface(aWidth, aHeight, aTransparent);
22   return true;
23 }
24 
Attach(Handle aHandle,uint32_t aWidth,uint32_t aHeight,bool aTransparent)25 bool SharedDIBSurface::Attach(Handle aHandle, uint32_t aWidth, uint32_t aHeight,
26                               bool aTransparent) {
27   nsresult rv = mSharedDIB.Attach(aHandle, aWidth, aHeight, aTransparent);
28   if (NS_FAILED(rv) || !mSharedDIB.IsValid()) return false;
29 
30   InitSurface(aWidth, aHeight, aTransparent);
31   return true;
32 }
33 
InitSurface(uint32_t aWidth,uint32_t aHeight,bool aTransparent)34 void SharedDIBSurface::InitSurface(uint32_t aWidth, uint32_t aHeight,
35                                    bool aTransparent) {
36   long stride = long(aWidth * SharedDIB::kBytesPerPixel);
37   unsigned char* data = reinterpret_cast<unsigned char*>(mSharedDIB.GetBits());
38 
39   gfxImageFormat format = aTransparent ? SurfaceFormat::A8R8G8B8_UINT32
40                                        : SurfaceFormat::X8R8G8B8_UINT32;
41 
42   gfxImageSurface::InitWithData(data, IntSize(aWidth, aHeight), stride, format);
43 
44   cairo_surface_set_user_data(mSurface, &SHAREDDIB_KEY, this, nullptr);
45 }
46 
IsSharedDIBSurface(gfxASurface * aSurface)47 bool SharedDIBSurface::IsSharedDIBSurface(gfxASurface* aSurface) {
48   return aSurface && aSurface->GetType() == gfxSurfaceType::Image &&
49          aSurface->GetData(&SHAREDDIB_KEY);
50 }
51 
52 }  // namespace gfx
53 }  // namespace mozilla
54