Avoid potential negative array index access to cached text.
[LibreOffice.git] / android / source / src / java / org / mozilla / gecko / gfx / TextLayer.java
blob023433a888c3f1a86ab857cadbd4419338ca7d7a
1 /* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 package org.mozilla.gecko.gfx;
8 import android.graphics.Bitmap;
9 import android.graphics.Canvas;
10 import android.graphics.Color;
11 import android.graphics.Paint;
12 import android.graphics.Typeface;
14 import org.libreoffice.kit.DirectBufferAllocator;
16 import java.nio.ByteBuffer;
18 /**
19 * Draws text on a layer. This is used for the frame rate meter.
21 public class TextLayer extends SingleTileLayer {
22 private final ByteBuffer mBuffer; // this buffer is owned by the BufferedCairoImage
23 private final IntSize mSize;
26 * This awkward pattern is necessary due to Java's restrictions on when one can call superclass
27 * constructors.
29 private TextLayer(ByteBuffer buffer, BufferedCairoImage image, IntSize size, String text) {
30 super(false, image);
31 mBuffer = buffer;
32 mSize = size;
33 renderText(text);
36 public static TextLayer create(IntSize size, String text) {
37 ByteBuffer buffer = DirectBufferAllocator.allocate(size.width * size.height * 4);
38 BufferedCairoImage image = new BufferedCairoImage(buffer, size.width, size.height,
39 CairoImage.FORMAT_ARGB32);
40 return new TextLayer(buffer, image, size, text);
43 public void setText(String text) {
44 renderText(text);
45 invalidate();
48 private void renderText(String text) {
49 Bitmap bitmap = Bitmap.createBitmap(mSize.width, mSize.height, Bitmap.Config.ARGB_8888);
50 Canvas canvas = new Canvas(bitmap);
52 Paint textPaint = new Paint();
53 textPaint.setAntiAlias(true);
54 textPaint.setColor(Color.WHITE);
55 textPaint.setFakeBoldText(true);
56 textPaint.setTextSize(18.0f);
57 textPaint.setTypeface(Typeface.DEFAULT_BOLD);
58 float width = textPaint.measureText(text) + 18.0f;
60 Paint backgroundPaint = new Paint();
61 backgroundPaint.setColor(Color.argb(127, 0, 0, 0));
62 canvas.drawRect(0.0f, 0.0f, width, 18.0f + 6.0f, backgroundPaint);
64 canvas.drawText(text, 6.0f, 18.0f, textPaint);
66 bitmap.copyPixelsToBuffer(mBuffer.asIntBuffer());