michael@0: /* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- michael@0: * This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: package org.mozilla.gecko.gfx; michael@0: michael@0: import org.mozilla.gecko.mozglue.DirectBufferAllocator; michael@0: michael@0: import android.graphics.Bitmap; michael@0: import android.util.Log; michael@0: michael@0: import java.nio.ByteBuffer; michael@0: michael@0: /** A Cairo image that simply saves a buffer of pixel data. */ michael@0: public class BufferedCairoImage extends CairoImage { michael@0: private ByteBuffer mBuffer; michael@0: private IntSize mSize; michael@0: private int mFormat; michael@0: michael@0: private static String LOGTAG = "GeckoBufferedCairoImage"; michael@0: michael@0: /** Creates a buffered Cairo image from a byte buffer. */ michael@0: public BufferedCairoImage(ByteBuffer inBuffer, int inWidth, int inHeight, int inFormat) { michael@0: setBuffer(inBuffer, inWidth, inHeight, inFormat); michael@0: } michael@0: michael@0: /** Creates a buffered Cairo image from an Android bitmap. */ michael@0: public BufferedCairoImage(Bitmap bitmap) { michael@0: setBitmap(bitmap); michael@0: } michael@0: michael@0: private synchronized void freeBuffer() { michael@0: mBuffer = DirectBufferAllocator.free(mBuffer); michael@0: } michael@0: michael@0: @Override michael@0: public void destroy() { michael@0: try { michael@0: freeBuffer(); michael@0: } catch (Exception ex) { michael@0: Log.e(LOGTAG, "error clearing buffer: ", ex); michael@0: } michael@0: } michael@0: michael@0: @Override michael@0: public ByteBuffer getBuffer() { return mBuffer; } michael@0: @Override michael@0: public IntSize getSize() { return mSize; } michael@0: @Override michael@0: public int getFormat() { return mFormat; } michael@0: michael@0: michael@0: public void setBuffer(ByteBuffer buffer, int width, int height, int format) { michael@0: freeBuffer(); michael@0: mBuffer = buffer; michael@0: mSize = new IntSize(width, height); michael@0: mFormat = format; michael@0: } michael@0: michael@0: public void setBitmap(Bitmap bitmap) { michael@0: mFormat = CairoUtils.bitmapConfigToCairoFormat(bitmap.getConfig()); michael@0: mSize = new IntSize(bitmap.getWidth(), bitmap.getHeight()); michael@0: michael@0: int bpp = CairoUtils.bitsPerPixelForCairoFormat(mFormat); michael@0: mBuffer = DirectBufferAllocator.allocate(mSize.getArea() * bpp); michael@0: bitmap.copyPixelsToBuffer(mBuffer.asIntBuffer()); michael@0: } michael@0: }