1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.gallery3d.glrenderer;
18 
19 import android.graphics.Rect;
20 
21 import java.nio.ByteBuffer;
22 import java.nio.ByteOrder;
23 
24 // See "frameworks/base/include/utils/ResourceTypes.h" for the format of
25 // NinePatch chunk.
26 class NinePatchChunk {
27 
28     public static final int NO_COLOR = 0x00000001;
29     public static final int TRANSPARENT_COLOR = 0x00000000;
30 
31     public Rect mPaddings = new Rect();
32 
33     public int mDivX[];
34     public int mDivY[];
35     public int mColor[];
36 
readIntArray(int[] data, ByteBuffer buffer)37     private static void readIntArray(int[] data, ByteBuffer buffer) {
38         for (int i = 0, n = data.length; i < n; ++i) {
39             data[i] = buffer.getInt();
40         }
41     }
42 
checkDivCount(int length)43     private static void checkDivCount(int length) {
44         if (length == 0 || (length & 0x01) != 0) {
45             throw new RuntimeException("invalid nine-patch: " + length);
46         }
47     }
48 
deserialize(byte[] data)49     public static NinePatchChunk deserialize(byte[] data) {
50         ByteBuffer byteBuffer =
51                 ByteBuffer.wrap(data).order(ByteOrder.nativeOrder());
52 
53         byte wasSerialized = byteBuffer.get();
54         if (wasSerialized == 0) return null;
55 
56         NinePatchChunk chunk = new NinePatchChunk();
57         chunk.mDivX = new int[byteBuffer.get()];
58         chunk.mDivY = new int[byteBuffer.get()];
59         chunk.mColor = new int[byteBuffer.get()];
60 
61         checkDivCount(chunk.mDivX.length);
62         checkDivCount(chunk.mDivY.length);
63 
64         // skip 8 bytes
65         byteBuffer.getInt();
66         byteBuffer.getInt();
67 
68         chunk.mPaddings.left = byteBuffer.getInt();
69         chunk.mPaddings.right = byteBuffer.getInt();
70         chunk.mPaddings.top = byteBuffer.getInt();
71         chunk.mPaddings.bottom = byteBuffer.getInt();
72 
73         // skip 4 bytes
74         byteBuffer.getInt();
75 
76         readIntArray(chunk.mDivX, byteBuffer);
77         readIntArray(chunk.mDivY, byteBuffer);
78         readIntArray(chunk.mColor, byteBuffer);
79 
80         return chunk;
81     }
82 }