Home | History | Annotate | Download | only in utils
      1 /*
      2  * Copyright (C) 2005 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 //
     18 // Definitions of resource data structures.
     19 //
     20 #ifndef _LIBS_UTILS_RESOURCE_TYPES_H
     21 #define _LIBS_UTILS_RESOURCE_TYPES_H
     22 
     23 #include <utils/Asset.h>
     24 #include <utils/ByteOrder.h>
     25 #include <utils/Errors.h>
     26 #include <utils/String16.h>
     27 #include <utils/Vector.h>
     28 
     29 #include <utils/threads.h>
     30 
     31 #include <stdint.h>
     32 #include <sys/types.h>
     33 
     34 #include <android/configuration.h>
     35 
     36 namespace android {
     37 
     38 /** ********************************************************************
     39  *  PNG Extensions
     40  *
     41  *  New private chunks that may be placed in PNG images.
     42  *
     43  *********************************************************************** */
     44 
     45 /**
     46  * This chunk specifies how to split an image into segments for
     47  * scaling.
     48  *
     49  * There are J horizontal and K vertical segments.  These segments divide
     50  * the image into J*K regions as follows (where J=4 and K=3):
     51  *
     52  *      F0   S0    F1     S1
     53  *   +-----+----+------+-------+
     54  * S2|  0  |  1 |  2   |   3   |
     55  *   +-----+----+------+-------+
     56  *   |     |    |      |       |
     57  *   |     |    |      |       |
     58  * F2|  4  |  5 |  6   |   7   |
     59  *   |     |    |      |       |
     60  *   |     |    |      |       |
     61  *   +-----+----+------+-------+
     62  * S3|  8  |  9 |  10  |   11  |
     63  *   +-----+----+------+-------+
     64  *
     65  * Each horizontal and vertical segment is considered to by either
     66  * stretchable (marked by the Sx labels) or fixed (marked by the Fy
     67  * labels), in the horizontal or vertical axis, respectively. In the
     68  * above example, the first is horizontal segment (F0) is fixed, the
     69  * next is stretchable and then they continue to alternate. Note that
     70  * the segment list for each axis can begin or end with a stretchable
     71  * or fixed segment.
     72  *
     73  * The relative sizes of the stretchy segments indicates the relative
     74  * amount of stretchiness of the regions bordered by the segments.  For
     75  * example, regions 3, 7 and 11 above will take up more horizontal space
     76  * than regions 1, 5 and 9 since the horizontal segment associated with
     77  * the first set of regions is larger than the other set of regions.  The
     78  * ratios of the amount of horizontal (or vertical) space taken by any
     79  * two stretchable slices is exactly the ratio of their corresponding
     80  * segment lengths.
     81  *
     82  * xDivs and yDivs point to arrays of horizontal and vertical pixel
     83  * indices.  The first pair of Divs (in either array) indicate the
     84  * starting and ending points of the first stretchable segment in that
     85  * axis. The next pair specifies the next stretchable segment, etc. So
     86  * in the above example xDiv[0] and xDiv[1] specify the horizontal
     87  * coordinates for the regions labeled 1, 5 and 9.  xDiv[2] and
     88  * xDiv[3] specify the coordinates for regions 3, 7 and 11. Note that
     89  * the leftmost slices always start at x=0 and the rightmost slices
     90  * always end at the end of the image. So, for example, the regions 0,
     91  * 4 and 8 (which are fixed along the X axis) start at x value 0 and
     92  * go to xDiv[0] and slices 2, 6 and 10 start at xDiv[1] and end at
     93  * xDiv[2].
     94  *
     95  * The array pointed to by the colors field lists contains hints for
     96  * each of the regions.  They are ordered according left-to-right and
     97  * top-to-bottom as indicated above. For each segment that is a solid
     98  * color the array entry will contain that color value; otherwise it
     99  * will contain NO_COLOR.  Segments that are completely transparent
    100  * will always have the value TRANSPARENT_COLOR.
    101  *
    102  * The PNG chunk type is "npTc".
    103  */
    104 struct Res_png_9patch
    105 {
    106     Res_png_9patch() : wasDeserialized(false), xDivs(NULL),
    107                        yDivs(NULL), colors(NULL) { }
    108 
    109     int8_t wasDeserialized;
    110     int8_t numXDivs;
    111     int8_t numYDivs;
    112     int8_t numColors;
    113 
    114     // These tell where the next section of a patch starts.
    115     // For example, the first patch includes the pixels from
    116     // 0 to xDivs[0]-1 and the second patch includes the pixels
    117     // from xDivs[0] to xDivs[1]-1.
    118     // Note: allocation/free of these pointers is left to the caller.
    119     int32_t* xDivs;
    120     int32_t* yDivs;
    121 
    122     int32_t paddingLeft, paddingRight;
    123     int32_t paddingTop, paddingBottom;
    124 
    125     enum {
    126         // The 9 patch segment is not a solid color.
    127         NO_COLOR = 0x00000001,
    128 
    129         // The 9 patch segment is completely transparent.
    130         TRANSPARENT_COLOR = 0x00000000
    131     };
    132     // Note: allocation/free of this pointer is left to the caller.
    133     uint32_t* colors;
    134 
    135     // Convert data from device representation to PNG file representation.
    136     void deviceToFile();
    137     // Convert data from PNG file representation to device representation.
    138     void fileToDevice();
    139     // Serialize/Marshall the patch data into a newly malloc-ed block
    140     void* serialize();
    141     // Serialize/Marshall the patch data
    142     void serialize(void* outData);
    143     // Deserialize/Unmarshall the patch data
    144     static Res_png_9patch* deserialize(const void* data);
    145     // Compute the size of the serialized data structure
    146     size_t serializedSize();
    147 };
    148 
    149 /** ********************************************************************
    150  *  Base Types
    151  *
    152  *  These are standard types that are shared between multiple specific
    153  *  resource types.
    154  *
    155  *********************************************************************** */
    156 
    157 /**
    158  * Header that appears at the front of every data chunk in a resource.
    159  */
    160 struct ResChunk_header
    161 {
    162     // Type identifier for this chunk.  The meaning of this value depends
    163     // on the containing chunk.
    164     uint16_t type;
    165 
    166     // Size of the chunk header (in bytes).  Adding this value to
    167     // the address of the chunk allows you to find its associated data
    168     // (if any).
    169     uint16_t headerSize;
    170 
    171     // Total size of this chunk (in bytes).  This is the chunkSize plus
    172     // the size of any data associated with the chunk.  Adding this value
    173     // to the chunk allows you to completely skip its contents (including
    174     // any child chunks).  If this value is the same as chunkSize, there is
    175     // no data associated with the chunk.
    176     uint32_t size;
    177 };
    178 
    179 enum {
    180     RES_NULL_TYPE               = 0x0000,
    181     RES_STRING_POOL_TYPE        = 0x0001,
    182     RES_TABLE_TYPE              = 0x0002,
    183     RES_XML_TYPE                = 0x0003,
    184 
    185     // Chunk types in RES_XML_TYPE
    186     RES_XML_FIRST_CHUNK_TYPE    = 0x0100,
    187     RES_XML_START_NAMESPACE_TYPE= 0x0100,
    188     RES_XML_END_NAMESPACE_TYPE  = 0x0101,
    189     RES_XML_START_ELEMENT_TYPE  = 0x0102,
    190     RES_XML_END_ELEMENT_TYPE    = 0x0103,
    191     RES_XML_CDATA_TYPE          = 0x0104,
    192     RES_XML_LAST_CHUNK_TYPE     = 0x017f,
    193     // This contains a uint32_t array mapping strings in the string
    194     // pool back to resource identifiers.  It is optional.
    195     RES_XML_RESOURCE_MAP_TYPE   = 0x0180,
    196 
    197     // Chunk types in RES_TABLE_TYPE
    198     RES_TABLE_PACKAGE_TYPE      = 0x0200,
    199     RES_TABLE_TYPE_TYPE         = 0x0201,
    200     RES_TABLE_TYPE_SPEC_TYPE    = 0x0202
    201 };
    202 
    203 /**
    204  * Macros for building/splitting resource identifiers.
    205  */
    206 #define Res_VALIDID(resid) (resid != 0)
    207 #define Res_CHECKID(resid) ((resid&0xFFFF0000) != 0)
    208 #define Res_MAKEID(package, type, entry) \
    209     (((package+1)<<24) | (((type+1)&0xFF)<<16) | (entry&0xFFFF))
    210 #define Res_GETPACKAGE(id) ((id>>24)-1)
    211 #define Res_GETTYPE(id) (((id>>16)&0xFF)-1)
    212 #define Res_GETENTRY(id) (id&0xFFFF)
    213 
    214 #define Res_INTERNALID(resid) ((resid&0xFFFF0000) != 0 && (resid&0xFF0000) == 0)
    215 #define Res_MAKEINTERNAL(entry) (0x01000000 | (entry&0xFFFF))
    216 #define Res_MAKEARRAY(entry) (0x02000000 | (entry&0xFFFF))
    217 
    218 #define Res_MAXPACKAGE 255
    219 
    220 /**
    221  * Representation of a value in a resource, supplying type
    222  * information.
    223  */
    224 struct Res_value
    225 {
    226     // Number of bytes in this structure.
    227     uint16_t size;
    228 
    229     // Always set to 0.
    230     uint8_t res0;
    231 
    232     // Type of the data value.
    233     enum {
    234         // Contains no data.
    235         TYPE_NULL = 0x00,
    236         // The 'data' holds a ResTable_ref, a reference to another resource
    237         // table entry.
    238         TYPE_REFERENCE = 0x01,
    239         // The 'data' holds an attribute resource identifier.
    240         TYPE_ATTRIBUTE = 0x02,
    241         // The 'data' holds an index into the containing resource table's
    242         // global value string pool.
    243         TYPE_STRING = 0x03,
    244         // The 'data' holds a single-precision floating point number.
    245         TYPE_FLOAT = 0x04,
    246         // The 'data' holds a complex number encoding a dimension value,
    247         // such as "100in".
    248         TYPE_DIMENSION = 0x05,
    249         // The 'data' holds a complex number encoding a fraction of a
    250         // container.
    251         TYPE_FRACTION = 0x06,
    252 
    253         // Beginning of integer flavors...
    254         TYPE_FIRST_INT = 0x10,
    255 
    256         // The 'data' is a raw integer value of the form n..n.
    257         TYPE_INT_DEC = 0x10,
    258         // The 'data' is a raw integer value of the form 0xn..n.
    259         TYPE_INT_HEX = 0x11,
    260         // The 'data' is either 0 or 1, for input "false" or "true" respectively.
    261         TYPE_INT_BOOLEAN = 0x12,
    262 
    263         // Beginning of color integer flavors...
    264         TYPE_FIRST_COLOR_INT = 0x1c,
    265 
    266         // The 'data' is a raw integer value of the form #aarrggbb.
    267         TYPE_INT_COLOR_ARGB8 = 0x1c,
    268         // The 'data' is a raw integer value of the form #rrggbb.
    269         TYPE_INT_COLOR_RGB8 = 0x1d,
    270         // The 'data' is a raw integer value of the form #argb.
    271         TYPE_INT_COLOR_ARGB4 = 0x1e,
    272         // The 'data' is a raw integer value of the form #rgb.
    273         TYPE_INT_COLOR_RGB4 = 0x1f,
    274 
    275         // ...end of integer flavors.
    276         TYPE_LAST_COLOR_INT = 0x1f,
    277 
    278         // ...end of integer flavors.
    279         TYPE_LAST_INT = 0x1f
    280     };
    281     uint8_t dataType;
    282 
    283     // Structure of complex data values (TYPE_UNIT and TYPE_FRACTION)
    284     enum {
    285         // Where the unit type information is.  This gives us 16 possible
    286         // types, as defined below.
    287         COMPLEX_UNIT_SHIFT = 0,
    288         COMPLEX_UNIT_MASK = 0xf,
    289 
    290         // TYPE_DIMENSION: Value is raw pixels.
    291         COMPLEX_UNIT_PX = 0,
    292         // TYPE_DIMENSION: Value is Device Independent Pixels.
    293         COMPLEX_UNIT_DIP = 1,
    294         // TYPE_DIMENSION: Value is a Scaled device independent Pixels.
    295         COMPLEX_UNIT_SP = 2,
    296         // TYPE_DIMENSION: Value is in points.
    297         COMPLEX_UNIT_PT = 3,
    298         // TYPE_DIMENSION: Value is in inches.
    299         COMPLEX_UNIT_IN = 4,
    300         // TYPE_DIMENSION: Value is in millimeters.
    301         COMPLEX_UNIT_MM = 5,
    302 
    303         // TYPE_FRACTION: A basic fraction of the overall size.
    304         COMPLEX_UNIT_FRACTION = 0,
    305         // TYPE_FRACTION: A fraction of the parent size.
    306         COMPLEX_UNIT_FRACTION_PARENT = 1,
    307 
    308         // Where the radix information is, telling where the decimal place
    309         // appears in the mantissa.  This give us 4 possible fixed point
    310         // representations as defined below.
    311         COMPLEX_RADIX_SHIFT = 4,
    312         COMPLEX_RADIX_MASK = 0x3,
    313 
    314         // The mantissa is an integral number -- i.e., 0xnnnnnn.0
    315         COMPLEX_RADIX_23p0 = 0,
    316         // The mantissa magnitude is 16 bits -- i.e, 0xnnnn.nn
    317         COMPLEX_RADIX_16p7 = 1,
    318         // The mantissa magnitude is 8 bits -- i.e, 0xnn.nnnn
    319         COMPLEX_RADIX_8p15 = 2,
    320         // The mantissa magnitude is 0 bits -- i.e, 0x0.nnnnnn
    321         COMPLEX_RADIX_0p23 = 3,
    322 
    323         // Where the actual value is.  This gives us 23 bits of
    324         // precision.  The top bit is the sign.
    325         COMPLEX_MANTISSA_SHIFT = 8,
    326         COMPLEX_MANTISSA_MASK = 0xffffff
    327     };
    328 
    329     // The data for this item, as interpreted according to dataType.
    330     uint32_t data;
    331 
    332     void copyFrom_dtoh(const Res_value& src);
    333 };
    334 
    335 /**
    336  *  This is a reference to a unique entry (a ResTable_entry structure)
    337  *  in a resource table.  The value is structured as: 0xpptteeee,
    338  *  where pp is the package index, tt is the type index in that
    339  *  package, and eeee is the entry index in that type.  The package
    340  *  and type values start at 1 for the first item, to help catch cases
    341  *  where they have not been supplied.
    342  */
    343 struct ResTable_ref
    344 {
    345     uint32_t ident;
    346 };
    347 
    348 /**
    349  * Reference to a string in a string pool.
    350  */
    351 struct ResStringPool_ref
    352 {
    353     // Index into the string pool table (uint32_t-offset from the indices
    354     // immediately after ResStringPool_header) at which to find the location
    355     // of the string data in the pool.
    356     uint32_t index;
    357 };
    358 
    359 /** ********************************************************************
    360  *  String Pool
    361  *
    362  *  A set of strings that can be references by others through a
    363  *  ResStringPool_ref.
    364  *
    365  *********************************************************************** */
    366 
    367 /**
    368  * Definition for a pool of strings.  The data of this chunk is an
    369  * array of uint32_t providing indices into the pool, relative to
    370  * stringsStart.  At stringsStart are all of the UTF-16 strings
    371  * concatenated together; each starts with a uint16_t of the string's
    372  * length and each ends with a 0x0000 terminator.  If a string is >
    373  * 32767 characters, the high bit of the length is set meaning to take
    374  * those 15 bits as a high word and it will be followed by another
    375  * uint16_t containing the low word.
    376  *
    377  * If styleCount is not zero, then immediately following the array of
    378  * uint32_t indices into the string table is another array of indices
    379  * into a style table starting at stylesStart.  Each entry in the
    380  * style table is an array of ResStringPool_span structures.
    381  */
    382 struct ResStringPool_header
    383 {
    384     struct ResChunk_header header;
    385 
    386     // Number of strings in this pool (number of uint32_t indices that follow
    387     // in the data).
    388     uint32_t stringCount;
    389 
    390     // Number of style span arrays in the pool (number of uint32_t indices
    391     // follow the string indices).
    392     uint32_t styleCount;
    393 
    394     // Flags.
    395     enum {
    396         // If set, the string index is sorted by the string values (based
    397         // on strcmp16()).
    398         SORTED_FLAG = 1<<0,
    399 
    400         // String pool is encoded in UTF-8
    401         UTF8_FLAG = 1<<8
    402     };
    403     uint32_t flags;
    404 
    405     // Index from header of the string data.
    406     uint32_t stringsStart;
    407 
    408     // Index from header of the style data.
    409     uint32_t stylesStart;
    410 };
    411 
    412 /**
    413  * This structure defines a span of style information associated with
    414  * a string in the pool.
    415  */
    416 struct ResStringPool_span
    417 {
    418     enum {
    419         END = 0xFFFFFFFF
    420     };
    421 
    422     // This is the name of the span -- that is, the name of the XML
    423     // tag that defined it.  The special value END (0xFFFFFFFF) indicates
    424     // the end of an array of spans.
    425     ResStringPool_ref name;
    426 
    427     // The range of characters in the string that this span applies to.
    428     uint32_t firstChar, lastChar;
    429 };
    430 
    431 /**
    432  * Convenience class for accessing data in a ResStringPool resource.
    433  */
    434 class ResStringPool
    435 {
    436 public:
    437     ResStringPool();
    438     ResStringPool(const void* data, size_t size, bool copyData=false);
    439     ~ResStringPool();
    440 
    441     status_t setTo(const void* data, size_t size, bool copyData=false);
    442 
    443     status_t getError() const;
    444 
    445     void uninit();
    446 
    447     inline const char16_t* stringAt(const ResStringPool_ref& ref, size_t* outLen) const {
    448         return stringAt(ref.index, outLen);
    449     }
    450     const char16_t* stringAt(size_t idx, size_t* outLen) const;
    451 
    452     const char* string8At(size_t idx, size_t* outLen) const;
    453 
    454     const ResStringPool_span* styleAt(const ResStringPool_ref& ref) const;
    455     const ResStringPool_span* styleAt(size_t idx) const;
    456 
    457     ssize_t indexOfString(const char16_t* str, size_t strLen) const;
    458 
    459     size_t size() const;
    460 
    461 #ifndef HAVE_ANDROID_OS
    462     bool isUTF8() const;
    463 #endif
    464 
    465 private:
    466     status_t                    mError;
    467     void*                       mOwnedData;
    468     const ResStringPool_header* mHeader;
    469     size_t                      mSize;
    470     mutable Mutex               mDecodeLock;
    471     const uint32_t*             mEntries;
    472     const uint32_t*             mEntryStyles;
    473     const void*                 mStrings;
    474     char16_t**                  mCache;
    475     uint32_t                    mStringPoolSize;    // number of uint16_t
    476     const uint32_t*             mStyles;
    477     uint32_t                    mStylePoolSize;    // number of uint32_t
    478 };
    479 
    480 /** ********************************************************************
    481  *  XML Tree
    482  *
    483  *  Binary representation of an XML document.  This is designed to
    484  *  express everything in an XML document, in a form that is much
    485  *  easier to parse on the device.
    486  *
    487  *********************************************************************** */
    488 
    489 /**
    490  * XML tree header.  This appears at the front of an XML tree,
    491  * describing its content.  It is followed by a flat array of
    492  * ResXMLTree_node structures; the hierarchy of the XML document
    493  * is described by the occurrance of RES_XML_START_ELEMENT_TYPE
    494  * and corresponding RES_XML_END_ELEMENT_TYPE nodes in the array.
    495  */
    496 struct ResXMLTree_header
    497 {
    498     struct ResChunk_header header;
    499 };
    500 
    501 /**
    502  * Basic XML tree node.  A single item in the XML document.  Extended info
    503  * about the node can be found after header.headerSize.
    504  */
    505 struct ResXMLTree_node
    506 {
    507     struct ResChunk_header header;
    508 
    509     // Line number in original source file at which this element appeared.
    510     uint32_t lineNumber;
    511 
    512     // Optional XML comment that was associated with this element; -1 if none.
    513     struct ResStringPool_ref comment;
    514 };
    515 
    516 /**
    517  * Extended XML tree node for CDATA tags -- includes the CDATA string.
    518  * Appears header.headerSize bytes after a ResXMLTree_node.
    519  */
    520 struct ResXMLTree_cdataExt
    521 {
    522     // The raw CDATA character data.
    523     struct ResStringPool_ref data;
    524 
    525     // The typed value of the character data if this is a CDATA node.
    526     struct Res_value typedData;
    527 };
    528 
    529 /**
    530  * Extended XML tree node for namespace start/end nodes.
    531  * Appears header.headerSize bytes after a ResXMLTree_node.
    532  */
    533 struct ResXMLTree_namespaceExt
    534 {
    535     // The prefix of the namespace.
    536     struct ResStringPool_ref prefix;
    537 
    538     // The URI of the namespace.
    539     struct ResStringPool_ref uri;
    540 };
    541 
    542 /**
    543  * Extended XML tree node for element start/end nodes.
    544  * Appears header.headerSize bytes after a ResXMLTree_node.
    545  */
    546 struct ResXMLTree_endElementExt
    547 {
    548     // String of the full namespace of this element.
    549     struct ResStringPool_ref ns;
    550 
    551     // String name of this node if it is an ELEMENT; the raw
    552     // character data if this is a CDATA node.
    553     struct ResStringPool_ref name;
    554 };
    555 
    556 /**
    557  * Extended XML tree node for start tags -- includes attribute
    558  * information.
    559  * Appears header.headerSize bytes after a ResXMLTree_node.
    560  */
    561 struct ResXMLTree_attrExt
    562 {
    563     // String of the full namespace of this element.
    564     struct ResStringPool_ref ns;
    565 
    566     // String name of this node if it is an ELEMENT; the raw
    567     // character data if this is a CDATA node.
    568     struct ResStringPool_ref name;
    569 
    570     // Byte offset from the start of this structure where the attributes start.
    571     uint16_t attributeStart;
    572 
    573     // Size of the ResXMLTree_attribute structures that follow.
    574     uint16_t attributeSize;
    575 
    576     // Number of attributes associated with an ELEMENT.  These are
    577     // available as an array of ResXMLTree_attribute structures
    578     // immediately following this node.
    579     uint16_t attributeCount;
    580 
    581     // Index (1-based) of the "id" attribute. 0 if none.
    582     uint16_t idIndex;
    583 
    584     // Index (1-based) of the "class" attribute. 0 if none.
    585     uint16_t classIndex;
    586 
    587     // Index (1-based) of the "style" attribute. 0 if none.
    588     uint16_t styleIndex;
    589 };
    590 
    591 struct ResXMLTree_attribute
    592 {
    593     // Namespace of this attribute.
    594     struct ResStringPool_ref ns;
    595 
    596     // Name of this attribute.
    597     struct ResStringPool_ref name;
    598 
    599     // The original raw string value of this attribute.
    600     struct ResStringPool_ref rawValue;
    601 
    602     // Processesd typed value of this attribute.
    603     struct Res_value typedValue;
    604 };
    605 
    606 class ResXMLTree;
    607 
    608 class ResXMLParser
    609 {
    610 public:
    611     ResXMLParser(const ResXMLTree& tree);
    612 
    613     enum event_code_t {
    614         BAD_DOCUMENT = -1,
    615         START_DOCUMENT = 0,
    616         END_DOCUMENT = 1,
    617 
    618         FIRST_CHUNK_CODE = RES_XML_FIRST_CHUNK_TYPE,
    619 
    620         START_NAMESPACE = RES_XML_START_NAMESPACE_TYPE,
    621         END_NAMESPACE = RES_XML_END_NAMESPACE_TYPE,
    622         START_TAG = RES_XML_START_ELEMENT_TYPE,
    623         END_TAG = RES_XML_END_ELEMENT_TYPE,
    624         TEXT = RES_XML_CDATA_TYPE
    625     };
    626 
    627     struct ResXMLPosition
    628     {
    629         event_code_t                eventCode;
    630         const ResXMLTree_node*      curNode;
    631         const void*                 curExt;
    632     };
    633 
    634     void restart();
    635 
    636     const ResStringPool& getStrings() const;
    637 
    638     event_code_t getEventType() const;
    639     // Note, unlike XmlPullParser, the first call to next() will return
    640     // START_TAG of the first element.
    641     event_code_t next();
    642 
    643     // These are available for all nodes:
    644     int32_t getCommentID() const;
    645     const uint16_t* getComment(size_t* outLen) const;
    646     uint32_t getLineNumber() const;
    647 
    648     // This is available for TEXT:
    649     int32_t getTextID() const;
    650     const uint16_t* getText(size_t* outLen) const;
    651     ssize_t getTextValue(Res_value* outValue) const;
    652 
    653     // These are available for START_NAMESPACE and END_NAMESPACE:
    654     int32_t getNamespacePrefixID() const;
    655     const uint16_t* getNamespacePrefix(size_t* outLen) const;
    656     int32_t getNamespaceUriID() const;
    657     const uint16_t* getNamespaceUri(size_t* outLen) const;
    658 
    659     // These are available for START_TAG and END_TAG:
    660     int32_t getElementNamespaceID() const;
    661     const uint16_t* getElementNamespace(size_t* outLen) const;
    662     int32_t getElementNameID() const;
    663     const uint16_t* getElementName(size_t* outLen) const;
    664 
    665     // Remaining methods are for retrieving information about attributes
    666     // associated with a START_TAG:
    667 
    668     size_t getAttributeCount() const;
    669 
    670     // Returns -1 if no namespace, -2 if idx out of range.
    671     int32_t getAttributeNamespaceID(size_t idx) const;
    672     const uint16_t* getAttributeNamespace(size_t idx, size_t* outLen) const;
    673 
    674     int32_t getAttributeNameID(size_t idx) const;
    675     const uint16_t* getAttributeName(size_t idx, size_t* outLen) const;
    676     uint32_t getAttributeNameResID(size_t idx) const;
    677 
    678     int32_t getAttributeValueStringID(size_t idx) const;
    679     const uint16_t* getAttributeStringValue(size_t idx, size_t* outLen) const;
    680 
    681     int32_t getAttributeDataType(size_t idx) const;
    682     int32_t getAttributeData(size_t idx) const;
    683     ssize_t getAttributeValue(size_t idx, Res_value* outValue) const;
    684 
    685     ssize_t indexOfAttribute(const char* ns, const char* attr) const;
    686     ssize_t indexOfAttribute(const char16_t* ns, size_t nsLen,
    687                              const char16_t* attr, size_t attrLen) const;
    688 
    689     ssize_t indexOfID() const;
    690     ssize_t indexOfClass() const;
    691     ssize_t indexOfStyle() const;
    692 
    693     void getPosition(ResXMLPosition* pos) const;
    694     void setPosition(const ResXMLPosition& pos);
    695 
    696 private:
    697     friend class ResXMLTree;
    698 
    699     event_code_t nextNode();
    700 
    701     const ResXMLTree&           mTree;
    702     event_code_t                mEventCode;
    703     const ResXMLTree_node*      mCurNode;
    704     const void*                 mCurExt;
    705 };
    706 
    707 /**
    708  * Convenience class for accessing data in a ResXMLTree resource.
    709  */
    710 class ResXMLTree : public ResXMLParser
    711 {
    712 public:
    713     ResXMLTree();
    714     ResXMLTree(const void* data, size_t size, bool copyData=false);
    715     ~ResXMLTree();
    716 
    717     status_t setTo(const void* data, size_t size, bool copyData=false);
    718 
    719     status_t getError() const;
    720 
    721     void uninit();
    722 
    723 private:
    724     friend class ResXMLParser;
    725 
    726     status_t validateNode(const ResXMLTree_node* node) const;
    727 
    728     status_t                    mError;
    729     void*                       mOwnedData;
    730     const ResXMLTree_header*    mHeader;
    731     size_t                      mSize;
    732     const uint8_t*              mDataEnd;
    733     ResStringPool               mStrings;
    734     const uint32_t*             mResIds;
    735     size_t                      mNumResIds;
    736     const ResXMLTree_node*      mRootNode;
    737     const void*                 mRootExt;
    738     event_code_t                mRootCode;
    739 };
    740 
    741 /** ********************************************************************
    742  *  RESOURCE TABLE
    743  *
    744  *********************************************************************** */
    745 
    746 /**
    747  * Header for a resource table.  Its data contains a series of
    748  * additional chunks:
    749  *   * A ResStringPool_header containing all table values.
    750  *   * One or more ResTable_package chunks.
    751  *
    752  * Specific entries within a resource table can be uniquely identified
    753  * with a single integer as defined by the ResTable_ref structure.
    754  */
    755 struct ResTable_header
    756 {
    757     struct ResChunk_header header;
    758 
    759     // The number of ResTable_package structures.
    760     uint32_t packageCount;
    761 };
    762 
    763 /**
    764  * A collection of resource data types within a package.  Followed by
    765  * one or more ResTable_type and ResTable_typeSpec structures containing the
    766  * entry values for each resource type.
    767  */
    768 struct ResTable_package
    769 {
    770     struct ResChunk_header header;
    771 
    772     // If this is a base package, its ID.  Package IDs start
    773     // at 1 (corresponding to the value of the package bits in a
    774     // resource identifier).  0 means this is not a base package.
    775     uint32_t id;
    776 
    777     // Actual name of this package, \0-terminated.
    778     char16_t name[128];
    779 
    780     // Offset to a ResStringPool_header defining the resource
    781     // type symbol table.  If zero, this package is inheriting from
    782     // another base package (overriding specific values in it).
    783     uint32_t typeStrings;
    784 
    785     // Last index into typeStrings that is for public use by others.
    786     uint32_t lastPublicType;
    787 
    788     // Offset to a ResStringPool_header defining the resource
    789     // key symbol table.  If zero, this package is inheriting from
    790     // another base package (overriding specific values in it).
    791     uint32_t keyStrings;
    792 
    793     // Last index into keyStrings that is for public use by others.
    794     uint32_t lastPublicKey;
    795 };
    796 
    797 /**
    798  * Describes a particular resource configuration.
    799  */
    800 struct ResTable_config
    801 {
    802     // Number of bytes in this structure.
    803     uint32_t size;
    804 
    805     union {
    806         struct {
    807             // Mobile country code (from SIM).  0 means "any".
    808             uint16_t mcc;
    809             // Mobile network code (from SIM).  0 means "any".
    810             uint16_t mnc;
    811         };
    812         uint32_t imsi;
    813     };
    814 
    815     union {
    816         struct {
    817             // \0\0 means "any".  Otherwise, en, fr, etc.
    818             char language[2];
    819 
    820             // \0\0 means "any".  Otherwise, US, CA, etc.
    821             char country[2];
    822         };
    823         uint32_t locale;
    824     };
    825 
    826     enum {
    827         ORIENTATION_ANY  = ACONFIGURATION_ORIENTATION_ANY,
    828         ORIENTATION_PORT = ACONFIGURATION_ORIENTATION_PORT,
    829         ORIENTATION_LAND = ACONFIGURATION_ORIENTATION_LAND,
    830         ORIENTATION_SQUARE = ACONFIGURATION_ORIENTATION_SQUARE,
    831     };
    832 
    833     enum {
    834         TOUCHSCREEN_ANY  = ACONFIGURATION_TOUCHSCREEN_ANY,
    835         TOUCHSCREEN_NOTOUCH  = ACONFIGURATION_TOUCHSCREEN_NOTOUCH,
    836         TOUCHSCREEN_STYLUS  = ACONFIGURATION_TOUCHSCREEN_STYLUS,
    837         TOUCHSCREEN_FINGER  = ACONFIGURATION_TOUCHSCREEN_FINGER,
    838     };
    839 
    840     enum {
    841         DENSITY_DEFAULT = ACONFIGURATION_DENSITY_DEFAULT,
    842         DENSITY_LOW = ACONFIGURATION_DENSITY_LOW,
    843         DENSITY_MEDIUM = ACONFIGURATION_DENSITY_MEDIUM,
    844         DENSITY_TV = ACONFIGURATION_DENSITY_TV,
    845         DENSITY_HIGH = ACONFIGURATION_DENSITY_HIGH,
    846         DENSITY_NONE = ACONFIGURATION_DENSITY_NONE
    847     };
    848 
    849     union {
    850         struct {
    851             uint8_t orientation;
    852             uint8_t touchscreen;
    853             uint16_t density;
    854         };
    855         uint32_t screenType;
    856     };
    857 
    858     enum {
    859         KEYBOARD_ANY  = ACONFIGURATION_KEYBOARD_ANY,
    860         KEYBOARD_NOKEYS  = ACONFIGURATION_KEYBOARD_NOKEYS,
    861         KEYBOARD_QWERTY  = ACONFIGURATION_KEYBOARD_QWERTY,
    862         KEYBOARD_12KEY  = ACONFIGURATION_KEYBOARD_12KEY,
    863     };
    864 
    865     enum {
    866         NAVIGATION_ANY  = ACONFIGURATION_NAVIGATION_ANY,
    867         NAVIGATION_NONAV  = ACONFIGURATION_NAVIGATION_NONAV,
    868         NAVIGATION_DPAD  = ACONFIGURATION_NAVIGATION_DPAD,
    869         NAVIGATION_TRACKBALL  = ACONFIGURATION_NAVIGATION_TRACKBALL,
    870         NAVIGATION_WHEEL  = ACONFIGURATION_NAVIGATION_WHEEL,
    871     };
    872 
    873     enum {
    874         MASK_KEYSHIDDEN = 0x0003,
    875         KEYSHIDDEN_ANY = ACONFIGURATION_KEYSHIDDEN_ANY,
    876         KEYSHIDDEN_NO = ACONFIGURATION_KEYSHIDDEN_NO,
    877         KEYSHIDDEN_YES = ACONFIGURATION_KEYSHIDDEN_YES,
    878         KEYSHIDDEN_SOFT = ACONFIGURATION_KEYSHIDDEN_SOFT,
    879     };
    880 
    881     enum {
    882         MASK_NAVHIDDEN = 0x000c,
    883         SHIFT_NAVHIDDEN = 2,
    884         NAVHIDDEN_ANY = ACONFIGURATION_NAVHIDDEN_ANY << SHIFT_NAVHIDDEN,
    885         NAVHIDDEN_NO = ACONFIGURATION_NAVHIDDEN_NO << SHIFT_NAVHIDDEN,
    886         NAVHIDDEN_YES = ACONFIGURATION_NAVHIDDEN_YES << SHIFT_NAVHIDDEN,
    887     };
    888 
    889     union {
    890         struct {
    891             uint8_t keyboard;
    892             uint8_t navigation;
    893             uint8_t inputFlags;
    894             uint8_t inputPad0;
    895         };
    896         uint32_t input;
    897     };
    898 
    899     enum {
    900         SCREENWIDTH_ANY = 0
    901     };
    902 
    903     enum {
    904         SCREENHEIGHT_ANY = 0
    905     };
    906 
    907     union {
    908         struct {
    909             uint16_t screenWidth;
    910             uint16_t screenHeight;
    911         };
    912         uint32_t screenSize;
    913     };
    914 
    915     enum {
    916         SDKVERSION_ANY = 0
    917     };
    918 
    919     enum {
    920         MINORVERSION_ANY = 0
    921     };
    922 
    923     union {
    924         struct {
    925             uint16_t sdkVersion;
    926             // For now minorVersion must always be 0!!!  Its meaning
    927             // is currently undefined.
    928             uint16_t minorVersion;
    929         };
    930         uint32_t version;
    931     };
    932 
    933     enum {
    934         // screenLayout bits for screen size class.
    935         MASK_SCREENSIZE = 0x0f,
    936         SCREENSIZE_ANY = ACONFIGURATION_SCREENSIZE_ANY,
    937         SCREENSIZE_SMALL = ACONFIGURATION_SCREENSIZE_SMALL,
    938         SCREENSIZE_NORMAL = ACONFIGURATION_SCREENSIZE_NORMAL,
    939         SCREENSIZE_LARGE = ACONFIGURATION_SCREENSIZE_LARGE,
    940         SCREENSIZE_XLARGE = ACONFIGURATION_SCREENSIZE_XLARGE,
    941 
    942         // screenLayout bits for wide/long screen variation.
    943         MASK_SCREENLONG = 0x30,
    944         SHIFT_SCREENLONG = 4,
    945         SCREENLONG_ANY = ACONFIGURATION_SCREENLONG_ANY << SHIFT_SCREENLONG,
    946         SCREENLONG_NO = ACONFIGURATION_SCREENLONG_NO << SHIFT_SCREENLONG,
    947         SCREENLONG_YES = ACONFIGURATION_SCREENLONG_YES << SHIFT_SCREENLONG,
    948     };
    949 
    950     enum {
    951         // uiMode bits for the mode type.
    952         MASK_UI_MODE_TYPE = 0x0f,
    953         UI_MODE_TYPE_ANY = ACONFIGURATION_UI_MODE_TYPE_ANY,
    954         UI_MODE_TYPE_NORMAL = ACONFIGURATION_UI_MODE_TYPE_NORMAL,
    955         UI_MODE_TYPE_DESK = ACONFIGURATION_UI_MODE_TYPE_DESK,
    956         UI_MODE_TYPE_CAR = ACONFIGURATION_UI_MODE_TYPE_CAR,
    957         UI_MODE_TYPE_TELEVISION = ACONFIGURATION_UI_MODE_TYPE_TELEVISION,
    958 
    959         // uiMode bits for the night switch.
    960         MASK_UI_MODE_NIGHT = 0x30,
    961         SHIFT_UI_MODE_NIGHT = 4,
    962         UI_MODE_NIGHT_ANY = ACONFIGURATION_UI_MODE_NIGHT_ANY << SHIFT_UI_MODE_NIGHT,
    963         UI_MODE_NIGHT_NO = ACONFIGURATION_UI_MODE_NIGHT_NO << SHIFT_UI_MODE_NIGHT,
    964         UI_MODE_NIGHT_YES = ACONFIGURATION_UI_MODE_NIGHT_YES << SHIFT_UI_MODE_NIGHT,
    965     };
    966 
    967     union {
    968         struct {
    969             uint8_t screenLayout;
    970             uint8_t uiMode;
    971             uint16_t smallestScreenWidthDp;
    972         };
    973         uint32_t screenConfig;
    974     };
    975 
    976     union {
    977         struct {
    978             uint16_t screenWidthDp;
    979             uint16_t screenHeightDp;
    980         };
    981         uint32_t screenSizeDp;
    982     };
    983 
    984     inline void copyFromDeviceNoSwap(const ResTable_config& o) {
    985         const size_t size = dtohl(o.size);
    986         if (size >= sizeof(ResTable_config)) {
    987             *this = o;
    988         } else {
    989             memcpy(this, &o, size);
    990             memset(((uint8_t*)this)+size, 0, sizeof(ResTable_config)-size);
    991         }
    992     }
    993 
    994     inline void copyFromDtoH(const ResTable_config& o) {
    995         copyFromDeviceNoSwap(o);
    996         size = sizeof(ResTable_config);
    997         mcc = dtohs(mcc);
    998         mnc = dtohs(mnc);
    999         density = dtohs(density);
   1000         screenWidth = dtohs(screenWidth);
   1001         screenHeight = dtohs(screenHeight);
   1002         sdkVersion = dtohs(sdkVersion);
   1003         minorVersion = dtohs(minorVersion);
   1004         smallestScreenWidthDp = dtohs(smallestScreenWidthDp);
   1005         screenWidthDp = dtohs(screenWidthDp);
   1006         screenHeightDp = dtohs(screenHeightDp);
   1007     }
   1008 
   1009     inline void swapHtoD() {
   1010         size = htodl(size);
   1011         mcc = htods(mcc);
   1012         mnc = htods(mnc);
   1013         density = htods(density);
   1014         screenWidth = htods(screenWidth);
   1015         screenHeight = htods(screenHeight);
   1016         sdkVersion = htods(sdkVersion);
   1017         minorVersion = htods(minorVersion);
   1018         smallestScreenWidthDp = htods(smallestScreenWidthDp);
   1019         screenWidthDp = htods(screenWidthDp);
   1020         screenHeightDp = htods(screenHeightDp);
   1021     }
   1022 
   1023     inline int compare(const ResTable_config& o) const {
   1024         int32_t diff = (int32_t)(imsi - o.imsi);
   1025         if (diff != 0) return diff;
   1026         diff = (int32_t)(locale - o.locale);
   1027         if (diff != 0) return diff;
   1028         diff = (int32_t)(screenType - o.screenType);
   1029         if (diff != 0) return diff;
   1030         diff = (int32_t)(input - o.input);
   1031         if (diff != 0) return diff;
   1032         diff = (int32_t)(screenSize - o.screenSize);
   1033         if (diff != 0) return diff;
   1034         diff = (int32_t)(version - o.version);
   1035         if (diff != 0) return diff;
   1036         diff = (int32_t)(screenLayout - o.screenLayout);
   1037         if (diff != 0) return diff;
   1038         diff = (int32_t)(uiMode - o.uiMode);
   1039         if (diff != 0) return diff;
   1040         diff = (int32_t)(smallestScreenWidthDp - o.smallestScreenWidthDp);
   1041         if (diff != 0) return diff;
   1042         diff = (int32_t)(screenSizeDp - o.screenSizeDp);
   1043         return (int)diff;
   1044     }
   1045 
   1046     // Flags indicating a set of config values.  These flag constants must
   1047     // match the corresponding ones in android.content.pm.ActivityInfo and
   1048     // attrs_manifest.xml.
   1049     enum {
   1050         CONFIG_MCC = ACONFIGURATION_MCC,
   1051         CONFIG_MNC = ACONFIGURATION_MCC,
   1052         CONFIG_LOCALE = ACONFIGURATION_LOCALE,
   1053         CONFIG_TOUCHSCREEN = ACONFIGURATION_TOUCHSCREEN,
   1054         CONFIG_KEYBOARD = ACONFIGURATION_KEYBOARD,
   1055         CONFIG_KEYBOARD_HIDDEN = ACONFIGURATION_KEYBOARD_HIDDEN,
   1056         CONFIG_NAVIGATION = ACONFIGURATION_NAVIGATION,
   1057         CONFIG_ORIENTATION = ACONFIGURATION_ORIENTATION,
   1058         CONFIG_DENSITY = ACONFIGURATION_DENSITY,
   1059         CONFIG_SCREEN_SIZE = ACONFIGURATION_SCREEN_SIZE,
   1060         CONFIG_SMALLEST_SCREEN_SIZE = ACONFIGURATION_SMALLEST_SCREEN_SIZE,
   1061         CONFIG_VERSION = ACONFIGURATION_VERSION,
   1062         CONFIG_SCREEN_LAYOUT = ACONFIGURATION_SCREEN_LAYOUT,
   1063         CONFIG_UI_MODE = ACONFIGURATION_UI_MODE
   1064     };
   1065 
   1066     // Compare two configuration, returning CONFIG_* flags set for each value
   1067     // that is different.
   1068     inline int diff(const ResTable_config& o) const {
   1069         int diffs = 0;
   1070         if (mcc != o.mcc) diffs |= CONFIG_MCC;
   1071         if (mnc != o.mnc) diffs |= CONFIG_MNC;
   1072         if (locale != o.locale) diffs |= CONFIG_LOCALE;
   1073         if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION;
   1074         if (density != o.density) diffs |= CONFIG_DENSITY;
   1075         if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN;
   1076         if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0)
   1077                 diffs |= CONFIG_KEYBOARD_HIDDEN;
   1078         if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD;
   1079         if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION;
   1080         if (screenSize != o.screenSize) diffs |= CONFIG_SCREEN_SIZE;
   1081         if (version != o.version) diffs |= CONFIG_VERSION;
   1082         if (screenLayout != o.screenLayout) diffs |= CONFIG_SCREEN_LAYOUT;
   1083         if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE;
   1084         if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE;
   1085         if (screenSizeDp != o.screenSizeDp) diffs |= CONFIG_SCREEN_SIZE;
   1086         return diffs;
   1087     }
   1088 
   1089     // Return true if 'this' is more specific than 'o'.
   1090     inline bool
   1091     isMoreSpecificThan(const ResTable_config& o) const {
   1092         // The order of the following tests defines the importance of one
   1093         // configuration parameter over another.  Those tests first are more
   1094         // important, trumping any values in those following them.
   1095         if (imsi || o.imsi) {
   1096             if (mcc != o.mcc) {
   1097                 if (!mcc) return false;
   1098                 if (!o.mcc) return true;
   1099             }
   1100 
   1101             if (mnc != o.mnc) {
   1102                 if (!mnc) return false;
   1103                 if (!o.mnc) return true;
   1104             }
   1105         }
   1106 
   1107         if (locale || o.locale) {
   1108             if (language[0] != o.language[0]) {
   1109                 if (!language[0]) return false;
   1110                 if (!o.language[0]) return true;
   1111             }
   1112 
   1113             if (country[0] != o.country[0]) {
   1114                 if (!country[0]) return false;
   1115                 if (!o.country[0]) return true;
   1116             }
   1117         }
   1118 
   1119         if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
   1120             if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
   1121                 if (!smallestScreenWidthDp) return false;
   1122                 if (!o.smallestScreenWidthDp) return true;
   1123             }
   1124         }
   1125 
   1126         if (screenSizeDp || o.screenSizeDp) {
   1127             if (screenWidthDp != o.screenWidthDp) {
   1128                 if (!screenWidthDp) return false;
   1129                 if (!o.screenWidthDp) return true;
   1130             }
   1131 
   1132             if (screenHeightDp != o.screenHeightDp) {
   1133                 if (!screenHeightDp) return false;
   1134                 if (!o.screenHeightDp) return true;
   1135             }
   1136         }
   1137 
   1138         if (screenLayout || o.screenLayout) {
   1139             if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0) {
   1140                 if (!(screenLayout & MASK_SCREENSIZE)) return false;
   1141                 if (!(o.screenLayout & MASK_SCREENSIZE)) return true;
   1142             }
   1143             if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0) {
   1144                 if (!(screenLayout & MASK_SCREENLONG)) return false;
   1145                 if (!(o.screenLayout & MASK_SCREENLONG)) return true;
   1146             }
   1147         }
   1148 
   1149         if (orientation != o.orientation) {
   1150             if (!orientation) return false;
   1151             if (!o.orientation) return true;
   1152         }
   1153 
   1154         if (uiMode || o.uiMode) {
   1155             if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0) {
   1156                 if (!(uiMode & MASK_UI_MODE_TYPE)) return false;
   1157                 if (!(o.uiMode & MASK_UI_MODE_TYPE)) return true;
   1158             }
   1159             if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0) {
   1160                 if (!(uiMode & MASK_UI_MODE_NIGHT)) return false;
   1161                 if (!(o.uiMode & MASK_UI_MODE_NIGHT)) return true;
   1162             }
   1163         }
   1164 
   1165         // density is never 'more specific'
   1166         // as the default just equals 160
   1167 
   1168         if (touchscreen != o.touchscreen) {
   1169             if (!touchscreen) return false;
   1170             if (!o.touchscreen) return true;
   1171         }
   1172 
   1173         if (input || o.input) {
   1174             if (((inputFlags^o.inputFlags) & MASK_KEYSHIDDEN) != 0) {
   1175                 if (!(inputFlags & MASK_KEYSHIDDEN)) return false;
   1176                 if (!(o.inputFlags & MASK_KEYSHIDDEN)) return true;
   1177             }
   1178 
   1179             if (((inputFlags^o.inputFlags) & MASK_NAVHIDDEN) != 0) {
   1180                 if (!(inputFlags & MASK_NAVHIDDEN)) return false;
   1181                 if (!(o.inputFlags & MASK_NAVHIDDEN)) return true;
   1182             }
   1183 
   1184             if (keyboard != o.keyboard) {
   1185                 if (!keyboard) return false;
   1186                 if (!o.keyboard) return true;
   1187             }
   1188 
   1189             if (navigation != o.navigation) {
   1190                 if (!navigation) return false;
   1191                 if (!o.navigation) return true;
   1192             }
   1193         }
   1194 
   1195         if (screenSize || o.screenSize) {
   1196             if (screenWidth != o.screenWidth) {
   1197                 if (!screenWidth) return false;
   1198                 if (!o.screenWidth) return true;
   1199             }
   1200 
   1201             if (screenHeight != o.screenHeight) {
   1202                 if (!screenHeight) return false;
   1203                 if (!o.screenHeight) return true;
   1204             }
   1205         }
   1206 
   1207         if (version || o.version) {
   1208             if (sdkVersion != o.sdkVersion) {
   1209                 if (!sdkVersion) return false;
   1210                 if (!o.sdkVersion) return true;
   1211             }
   1212 
   1213             if (minorVersion != o.minorVersion) {
   1214                 if (!minorVersion) return false;
   1215                 if (!o.minorVersion) return true;
   1216             }
   1217         }
   1218         return false;
   1219     }
   1220 
   1221     // Return true if 'this' is a better match than 'o' for the 'requested'
   1222     // configuration.  This assumes that match() has already been used to
   1223     // remove any configurations that don't match the requested configuration
   1224     // at all; if they are not first filtered, non-matching results can be
   1225     // considered better than matching ones.
   1226     // The general rule per attribute: if the request cares about an attribute
   1227     // (it normally does), if the two (this and o) are equal it's a tie.  If
   1228     // they are not equal then one must be generic because only generic and
   1229     // '==requested' will pass the match() call.  So if this is not generic,
   1230     // it wins.  If this IS generic, o wins (return false).
   1231     inline bool
   1232     isBetterThan(const ResTable_config& o,
   1233             const ResTable_config* requested) const {
   1234         if (requested) {
   1235             if (imsi || o.imsi) {
   1236                 if ((mcc != o.mcc) && requested->mcc) {
   1237                     return (mcc);
   1238                 }
   1239 
   1240                 if ((mnc != o.mnc) && requested->mnc) {
   1241                     return (mnc);
   1242                 }
   1243             }
   1244 
   1245             if (locale || o.locale) {
   1246                 if ((language[0] != o.language[0]) && requested->language[0]) {
   1247                     return (language[0]);
   1248                 }
   1249 
   1250                 if ((country[0] != o.country[0]) && requested->country[0]) {
   1251                     return (country[0]);
   1252                 }
   1253             }
   1254 
   1255             if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
   1256                 // The configuration closest to the actual size is best.
   1257                 // We assume that larger configs have already been filtered
   1258                 // out at this point.  That means we just want the largest one.
   1259                 return smallestScreenWidthDp >= o.smallestScreenWidthDp;
   1260             }
   1261 
   1262             if (screenSizeDp || o.screenSizeDp) {
   1263                 // "Better" is based on the sum of the difference between both
   1264                 // width and height from the requested dimensions.  We are
   1265                 // assuming the invalid configs (with smaller dimens) have
   1266                 // already been filtered.  Note that if a particular dimension
   1267                 // is unspecified, we will end up with a large value (the
   1268                 // difference between 0 and the requested dimension), which is
   1269                 // good since we will prefer a config that has specified a
   1270                 // dimension value.
   1271                 int myDelta = 0, otherDelta = 0;
   1272                 if (requested->screenWidthDp) {
   1273                     myDelta += requested->screenWidthDp - screenWidthDp;
   1274                     otherDelta += requested->screenWidthDp - o.screenWidthDp;
   1275                 }
   1276                 if (requested->screenHeightDp) {
   1277                     myDelta += requested->screenHeightDp - screenHeightDp;
   1278                     otherDelta += requested->screenHeightDp - o.screenHeightDp;
   1279                 }
   1280                 //LOGI("Comparing this %dx%d to other %dx%d in %dx%d: myDelta=%d otherDelta=%d",
   1281                 //    screenWidthDp, screenHeightDp, o.screenWidthDp, o.screenHeightDp,
   1282                 //    requested->screenWidthDp, requested->screenHeightDp, myDelta, otherDelta);
   1283                 return (myDelta <= otherDelta);
   1284             }
   1285 
   1286             if (screenLayout || o.screenLayout) {
   1287                 if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0
   1288                         && (requested->screenLayout & MASK_SCREENSIZE)) {
   1289                     // A little backwards compatibility here: undefined is
   1290                     // considered equivalent to normal.  But only if the
   1291                     // requested size is at least normal; otherwise, small
   1292                     // is better than the default.
   1293                     int mySL = (screenLayout & MASK_SCREENSIZE);
   1294                     int oSL = (o.screenLayout & MASK_SCREENSIZE);
   1295                     int fixedMySL = mySL;
   1296                     int fixedOSL = oSL;
   1297                     if ((requested->screenLayout & MASK_SCREENSIZE) >= SCREENSIZE_NORMAL) {
   1298                         if (fixedMySL == 0) fixedMySL = SCREENSIZE_NORMAL;
   1299                         if (fixedOSL == 0) fixedOSL = SCREENSIZE_NORMAL;
   1300                     }
   1301                     // For screen size, the best match is the one that is
   1302                     // closest to the requested screen size, but not over
   1303                     // (the not over part is dealt with in match() below).
   1304                     if (fixedMySL == fixedOSL) {
   1305                         // If the two are the same, but 'this' is actually
   1306                         // undefined, then the other is really a better match.
   1307                         if (mySL == 0) return false;
   1308                         return true;
   1309                     }
   1310                     return fixedMySL >= fixedOSL;
   1311                 }
   1312                 if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0
   1313                         && (requested->screenLayout & MASK_SCREENLONG)) {
   1314                     return (screenLayout & MASK_SCREENLONG);
   1315                 }
   1316             }
   1317 
   1318             if ((orientation != o.orientation) && requested->orientation) {
   1319                 return (orientation);
   1320             }
   1321 
   1322             if (uiMode || o.uiMode) {
   1323                 if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0
   1324                         && (requested->uiMode & MASK_UI_MODE_TYPE)) {
   1325                     return (uiMode & MASK_UI_MODE_TYPE);
   1326                 }
   1327                 if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0
   1328                         && (requested->uiMode & MASK_UI_MODE_NIGHT)) {
   1329                     return (uiMode & MASK_UI_MODE_NIGHT);
   1330                 }
   1331             }
   1332 
   1333             if (screenType || o.screenType) {
   1334                 if (density != o.density) {
   1335                     // density is tough.  Any density is potentially useful
   1336                     // because the system will scale it.  Scaling down
   1337                     // is generally better than scaling up.
   1338                     // Default density counts as 160dpi (the system default)
   1339                     // TODO - remove 160 constants
   1340                     int h = (density?density:160);
   1341                     int l = (o.density?o.density:160);
   1342                     bool bImBigger = true;
   1343                     if (l > h) {
   1344                         int t = h;
   1345                         h = l;
   1346                         l = t;
   1347                         bImBigger = false;
   1348                     }
   1349 
   1350                     int reqValue = (requested->density?requested->density:160);
   1351                     if (reqValue >= h) {
   1352                         // requested value higher than both l and h, give h
   1353                         return bImBigger;
   1354                     }
   1355                     if (l >= reqValue) {
   1356                         // requested value lower than both l and h, give l
   1357                         return !bImBigger;
   1358                     }
   1359                     // saying that scaling down is 2x better than up
   1360                     if (((2 * l) - reqValue) * h > reqValue * reqValue) {
   1361                         return !bImBigger;
   1362                     } else {
   1363                         return bImBigger;
   1364                     }
   1365                 }
   1366 
   1367                 if ((touchscreen != o.touchscreen) && requested->touchscreen) {
   1368                     return (touchscreen);
   1369                 }
   1370             }
   1371 
   1372             if (input || o.input) {
   1373                 const int keysHidden = inputFlags & MASK_KEYSHIDDEN;
   1374                 const int oKeysHidden = o.inputFlags & MASK_KEYSHIDDEN;
   1375                 if (keysHidden != oKeysHidden) {
   1376                     const int reqKeysHidden =
   1377                             requested->inputFlags & MASK_KEYSHIDDEN;
   1378                     if (reqKeysHidden) {
   1379 
   1380                         if (!keysHidden) return false;
   1381                         if (!oKeysHidden) return true;
   1382                         // For compatibility, we count KEYSHIDDEN_NO as being
   1383                         // the same as KEYSHIDDEN_SOFT.  Here we disambiguate
   1384                         // these by making an exact match more specific.
   1385                         if (reqKeysHidden == keysHidden) return true;
   1386                         if (reqKeysHidden == oKeysHidden) return false;
   1387                     }
   1388                 }
   1389 
   1390                 const int navHidden = inputFlags & MASK_NAVHIDDEN;
   1391                 const int oNavHidden = o.inputFlags & MASK_NAVHIDDEN;
   1392                 if (navHidden != oNavHidden) {
   1393                     const int reqNavHidden =
   1394                             requested->inputFlags & MASK_NAVHIDDEN;
   1395                     if (reqNavHidden) {
   1396 
   1397                         if (!navHidden) return false;
   1398                         if (!oNavHidden) return true;
   1399                     }
   1400                 }
   1401 
   1402                 if ((keyboard != o.keyboard) && requested->keyboard) {
   1403                     return (keyboard);
   1404                 }
   1405 
   1406                 if ((navigation != o.navigation) && requested->navigation) {
   1407                     return (navigation);
   1408                 }
   1409             }
   1410 
   1411             if (screenSize || o.screenSize) {
   1412                 // "Better" is based on the sum of the difference between both
   1413                 // width and height from the requested dimensions.  We are
   1414                 // assuming the invalid configs (with smaller sizes) have
   1415                 // already been filtered.  Note that if a particular dimension
   1416                 // is unspecified, we will end up with a large value (the
   1417                 // difference between 0 and the requested dimension), which is
   1418                 // good since we will prefer a config that has specified a
   1419                 // size value.
   1420                 int myDelta = 0, otherDelta = 0;
   1421                 if (requested->screenWidth) {
   1422                     myDelta += requested->screenWidth - screenWidth;
   1423                     otherDelta += requested->screenWidth - o.screenWidth;
   1424                 }
   1425                 if (requested->screenHeight) {
   1426                     myDelta += requested->screenHeight - screenHeight;
   1427                     otherDelta += requested->screenHeight - o.screenHeight;
   1428                 }
   1429                 return (myDelta <= otherDelta);
   1430             }
   1431 
   1432             if (version || o.version) {
   1433                 if ((sdkVersion != o.sdkVersion) && requested->sdkVersion) {
   1434                     return (sdkVersion > o.sdkVersion);
   1435                 }
   1436 
   1437                 if ((minorVersion != o.minorVersion) &&
   1438                         requested->minorVersion) {
   1439                     return (minorVersion);
   1440                 }
   1441             }
   1442 
   1443             return false;
   1444         }
   1445         return isMoreSpecificThan(o);
   1446     }
   1447 
   1448     // Return true if 'this' can be considered a match for the parameters in
   1449     // 'settings'.
   1450     // Note this is asymetric.  A default piece of data will match every request
   1451     // but a request for the default should not match odd specifics
   1452     // (ie, request with no mcc should not match a particular mcc's data)
   1453     // settings is the requested settings
   1454     inline bool match(const ResTable_config& settings) const {
   1455         if (imsi != 0) {
   1456             if (mcc != 0 && mcc != settings.mcc) {
   1457                 return false;
   1458             }
   1459             if (mnc != 0 && mnc != settings.mnc) {
   1460                 return false;
   1461             }
   1462         }
   1463         if (locale != 0) {
   1464             if (language[0] != 0
   1465                 && (language[0] != settings.language[0]
   1466                     || language[1] != settings.language[1])) {
   1467                 return false;
   1468             }
   1469             if (country[0] != 0
   1470                 && (country[0] != settings.country[0]
   1471                     || country[1] != settings.country[1])) {
   1472                 return false;
   1473             }
   1474         }
   1475         if (screenConfig != 0) {
   1476             const int screenSize = screenLayout&MASK_SCREENSIZE;
   1477             const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE;
   1478             // Any screen sizes for larger screens than the setting do not
   1479             // match.
   1480             if (screenSize != 0 && screenSize > setScreenSize) {
   1481                 return false;
   1482             }
   1483 
   1484             const int screenLong = screenLayout&MASK_SCREENLONG;
   1485             const int setScreenLong = settings.screenLayout&MASK_SCREENLONG;
   1486             if (screenLong != 0 && screenLong != setScreenLong) {
   1487                 return false;
   1488             }
   1489 
   1490             const int uiModeType = uiMode&MASK_UI_MODE_TYPE;
   1491             const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE;
   1492             if (uiModeType != 0 && uiModeType != setUiModeType) {
   1493                 return false;
   1494             }
   1495 
   1496             const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT;
   1497             const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT;
   1498             if (uiModeNight != 0 && uiModeNight != setUiModeNight) {
   1499                 return false;
   1500             }
   1501 
   1502             if (smallestScreenWidthDp != 0
   1503                     && smallestScreenWidthDp > settings.smallestScreenWidthDp) {
   1504                 return false;
   1505             }
   1506         }
   1507         if (screenSizeDp != 0) {
   1508             if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) {
   1509                 //LOGI("Filtering out width %d in requested %d", screenWidthDp, settings.screenWidthDp);
   1510                 return false;
   1511             }
   1512             if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) {
   1513                 //LOGI("Filtering out height %d in requested %d", screenHeightDp, settings.screenHeightDp);
   1514                 return false;
   1515             }
   1516         }
   1517         if (screenType != 0) {
   1518             if (orientation != 0 && orientation != settings.orientation) {
   1519                 return false;
   1520             }
   1521             // density always matches - we can scale it.  See isBetterThan
   1522             if (touchscreen != 0 && touchscreen != settings.touchscreen) {
   1523                 return false;
   1524             }
   1525         }
   1526         if (input != 0) {
   1527             const int keysHidden = inputFlags&MASK_KEYSHIDDEN;
   1528             const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN;
   1529             if (keysHidden != 0 && keysHidden != setKeysHidden) {
   1530                 // For compatibility, we count a request for KEYSHIDDEN_NO as also
   1531                 // matching the more recent KEYSHIDDEN_SOFT.  Basically
   1532                 // KEYSHIDDEN_NO means there is some kind of keyboard available.
   1533                 //LOGI("Matching keysHidden: have=%d, config=%d\n", keysHidden, setKeysHidden);
   1534                 if (keysHidden != KEYSHIDDEN_NO || setKeysHidden != KEYSHIDDEN_SOFT) {
   1535                     //LOGI("No match!");
   1536                     return false;
   1537                 }
   1538             }
   1539             const int navHidden = inputFlags&MASK_NAVHIDDEN;
   1540             const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN;
   1541             if (navHidden != 0 && navHidden != setNavHidden) {
   1542                 return false;
   1543             }
   1544             if (keyboard != 0 && keyboard != settings.keyboard) {
   1545                 return false;
   1546             }
   1547             if (navigation != 0 && navigation != settings.navigation) {
   1548                 return false;
   1549             }
   1550         }
   1551         if (screenSize != 0) {
   1552             if (screenWidth != 0 && screenWidth > settings.screenWidth) {
   1553                 return false;
   1554             }
   1555             if (screenHeight != 0 && screenHeight > settings.screenHeight) {
   1556                 return false;
   1557             }
   1558         }
   1559         if (version != 0) {
   1560             if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) {
   1561                 return false;
   1562             }
   1563             if (minorVersion != 0 && minorVersion != settings.minorVersion) {
   1564                 return false;
   1565             }
   1566         }
   1567         return true;
   1568     }
   1569 
   1570     void getLocale(char str[6]) const {
   1571         memset(str, 0, 6);
   1572         if (language[0]) {
   1573             str[0] = language[0];
   1574             str[1] = language[1];
   1575             if (country[0]) {
   1576                 str[2] = '_';
   1577                 str[3] = country[0];
   1578                 str[4] = country[1];
   1579             }
   1580         }
   1581     }
   1582 
   1583     String8 toString() const {
   1584         char buf[200];
   1585         sprintf(buf, "imsi=%d/%d lang=%c%c reg=%c%c orient=%d touch=%d dens=%d "
   1586                 "kbd=%d nav=%d input=%d ssz=%dx%d sw%ddp w%ddp h%ddp sz=%d long=%d "
   1587                 "ui=%d night=%d vers=%d.%d",
   1588                 mcc, mnc,
   1589                 language[0] ? language[0] : '-', language[1] ? language[1] : '-',
   1590                 country[0] ? country[0] : '-', country[1] ? country[1] : '-',
   1591                 orientation, touchscreen, density, keyboard, navigation, inputFlags,
   1592                 screenWidth, screenHeight, smallestScreenWidthDp, screenWidthDp, screenHeightDp,
   1593                 screenLayout&MASK_SCREENSIZE, screenLayout&MASK_SCREENLONG,
   1594                 uiMode&MASK_UI_MODE_TYPE, uiMode&MASK_UI_MODE_NIGHT,
   1595                 sdkVersion, minorVersion);
   1596         return String8(buf);
   1597     }
   1598 };
   1599 
   1600 /**
   1601  * A specification of the resources defined by a particular type.
   1602  *
   1603  * There should be one of these chunks for each resource type.
   1604  *
   1605  * This structure is followed by an array of integers providing the set of
   1606  * configuation change flags (ResTable_config::CONFIG_*) that have multiple
   1607  * resources for that configuration.  In addition, the high bit is set if that
   1608  * resource has been made public.
   1609  */
   1610 struct ResTable_typeSpec
   1611 {
   1612     struct ResChunk_header header;
   1613 
   1614     // The type identifier this chunk is holding.  Type IDs start
   1615     // at 1 (corresponding to the value of the type bits in a
   1616     // resource identifier).  0 is invalid.
   1617     uint8_t id;
   1618 
   1619     // Must be 0.
   1620     uint8_t res0;
   1621     // Must be 0.
   1622     uint16_t res1;
   1623 
   1624     // Number of uint32_t entry configuration masks that follow.
   1625     uint32_t entryCount;
   1626 
   1627     enum {
   1628         // Additional flag indicating an entry is public.
   1629         SPEC_PUBLIC = 0x40000000
   1630     };
   1631 };
   1632 
   1633 /**
   1634  * A collection of resource entries for a particular resource data
   1635  * type. Followed by an array of uint32_t defining the resource
   1636  * values, corresponding to the array of type strings in the
   1637  * ResTable_package::typeStrings string block. Each of these hold an
   1638  * index from entriesStart; a value of NO_ENTRY means that entry is
   1639  * not defined.
   1640  *
   1641  * There may be multiple of these chunks for a particular resource type,
   1642  * supply different configuration variations for the resource values of
   1643  * that type.
   1644  *
   1645  * It would be nice to have an additional ordered index of entries, so
   1646  * we can do a binary search if trying to find a resource by string name.
   1647  */
   1648 struct ResTable_type
   1649 {
   1650     struct ResChunk_header header;
   1651 
   1652     enum {
   1653         NO_ENTRY = 0xFFFFFFFF
   1654     };
   1655 
   1656     // The type identifier this chunk is holding.  Type IDs start
   1657     // at 1 (corresponding to the value of the type bits in a
   1658     // resource identifier).  0 is invalid.
   1659     uint8_t id;
   1660 
   1661     // Must be 0.
   1662     uint8_t res0;
   1663     // Must be 0.
   1664     uint16_t res1;
   1665 
   1666     // Number of uint32_t entry indices that follow.
   1667     uint32_t entryCount;
   1668 
   1669     // Offset from header where ResTable_entry data starts.
   1670     uint32_t entriesStart;
   1671 
   1672     // Configuration this collection of entries is designed for.
   1673     ResTable_config config;
   1674 };
   1675 
   1676 /**
   1677  * This is the beginning of information about an entry in the resource
   1678  * table.  It holds the reference to the name of this entry, and is
   1679  * immediately followed by one of:
   1680  *   * A Res_value structure, if FLAG_COMPLEX is -not- set.
   1681  *   * An array of ResTable_map structures, if FLAG_COMPLEX is set.
   1682  *     These supply a set of name/value mappings of data.
   1683  */
   1684 struct ResTable_entry
   1685 {
   1686     // Number of bytes in this structure.
   1687     uint16_t size;
   1688 
   1689     enum {
   1690         // If set, this is a complex entry, holding a set of name/value
   1691         // mappings.  It is followed by an array of ResTable_map structures.
   1692         FLAG_COMPLEX = 0x0001,
   1693         // If set, this resource has been declared public, so libraries
   1694         // are allowed to reference it.
   1695         FLAG_PUBLIC = 0x0002
   1696     };
   1697     uint16_t flags;
   1698 
   1699     // Reference into ResTable_package::keyStrings identifying this entry.
   1700     struct ResStringPool_ref key;
   1701 };
   1702 
   1703 /**
   1704  * Extended form of a ResTable_entry for map entries, defining a parent map
   1705  * resource from which to inherit values.
   1706  */
   1707 struct ResTable_map_entry : public ResTable_entry
   1708 {
   1709     // Resource identifier of the parent mapping, or 0 if there is none.
   1710     ResTable_ref parent;
   1711     // Number of name/value pairs that follow for FLAG_COMPLEX.
   1712     uint32_t count;
   1713 };
   1714 
   1715 /**
   1716  * A single name/value mapping that is part of a complex resource
   1717  * entry.
   1718  */
   1719 struct ResTable_map
   1720 {
   1721     // The resource identifier defining this mapping's name.  For attribute
   1722     // resources, 'name' can be one of the following special resource types
   1723     // to supply meta-data about the attribute; for all other resource types
   1724     // it must be an attribute resource.
   1725     ResTable_ref name;
   1726 
   1727     // Special values for 'name' when defining attribute resources.
   1728     enum {
   1729         // This entry holds the attribute's type code.
   1730         ATTR_TYPE = Res_MAKEINTERNAL(0),
   1731 
   1732         // For integral attributes, this is the minimum value it can hold.
   1733         ATTR_MIN = Res_MAKEINTERNAL(1),
   1734 
   1735         // For integral attributes, this is the maximum value it can hold.
   1736         ATTR_MAX = Res_MAKEINTERNAL(2),
   1737 
   1738         // Localization of this resource is can be encouraged or required with
   1739         // an aapt flag if this is set
   1740         ATTR_L10N = Res_MAKEINTERNAL(3),
   1741 
   1742         // for plural support, see android.content.res.PluralRules#attrForQuantity(int)
   1743         ATTR_OTHER = Res_MAKEINTERNAL(4),
   1744         ATTR_ZERO = Res_MAKEINTERNAL(5),
   1745         ATTR_ONE = Res_MAKEINTERNAL(6),
   1746         ATTR_TWO = Res_MAKEINTERNAL(7),
   1747         ATTR_FEW = Res_MAKEINTERNAL(8),
   1748         ATTR_MANY = Res_MAKEINTERNAL(9)
   1749 
   1750     };
   1751 
   1752     // Bit mask of allowed types, for use with ATTR_TYPE.
   1753     enum {
   1754         // No type has been defined for this attribute, use generic
   1755         // type handling.  The low 16 bits are for types that can be
   1756         // handled generically; the upper 16 require additional information
   1757         // in the bag so can not be handled generically for TYPE_ANY.
   1758         TYPE_ANY = 0x0000FFFF,
   1759 
   1760         // Attribute holds a references to another resource.
   1761         TYPE_REFERENCE = 1<<0,
   1762 
   1763         // Attribute holds a generic string.
   1764         TYPE_STRING = 1<<1,
   1765 
   1766         // Attribute holds an integer value.  ATTR_MIN and ATTR_MIN can
   1767         // optionally specify a constrained range of possible integer values.
   1768         TYPE_INTEGER = 1<<2,
   1769 
   1770         // Attribute holds a boolean integer.
   1771         TYPE_BOOLEAN = 1<<3,
   1772 
   1773         // Attribute holds a color value.
   1774         TYPE_COLOR = 1<<4,
   1775 
   1776         // Attribute holds a floating point value.
   1777         TYPE_FLOAT = 1<<5,
   1778 
   1779         // Attribute holds a dimension value, such as "20px".
   1780         TYPE_DIMENSION = 1<<6,
   1781 
   1782         // Attribute holds a fraction value, such as "20%".
   1783         TYPE_FRACTION = 1<<7,
   1784 
   1785         // Attribute holds an enumeration.  The enumeration values are
   1786         // supplied as additional entries in the map.
   1787         TYPE_ENUM = 1<<16,
   1788 
   1789         // Attribute holds a bitmaks of flags.  The flag bit values are
   1790         // supplied as additional entries in the map.
   1791         TYPE_FLAGS = 1<<17
   1792     };
   1793 
   1794     // Enum of localization modes, for use with ATTR_L10N.
   1795     enum {
   1796         L10N_NOT_REQUIRED = 0,
   1797         L10N_SUGGESTED    = 1
   1798     };
   1799 
   1800     // This mapping's value.
   1801     Res_value value;
   1802 };
   1803 
   1804 /**
   1805  * Convenience class for accessing data in a ResTable resource.
   1806  */
   1807 class ResTable
   1808 {
   1809 public:
   1810     ResTable();
   1811     ResTable(const void* data, size_t size, void* cookie,
   1812              bool copyData=false);
   1813     ~ResTable();
   1814 
   1815     status_t add(const void* data, size_t size, void* cookie,
   1816                  bool copyData=false, const void* idmap = NULL);
   1817     status_t add(Asset* asset, void* cookie,
   1818                  bool copyData=false, const void* idmap = NULL);
   1819     status_t add(ResTable* src);
   1820 
   1821     status_t getError() const;
   1822 
   1823     void uninit();
   1824 
   1825     struct resource_name
   1826     {
   1827         const char16_t* package;
   1828         size_t packageLen;
   1829         const char16_t* type;
   1830         size_t typeLen;
   1831         const char16_t* name;
   1832         size_t nameLen;
   1833     };
   1834 
   1835     bool getResourceName(uint32_t resID, resource_name* outName) const;
   1836 
   1837     /**
   1838      * Retrieve the value of a resource.  If the resource is found, returns a
   1839      * value >= 0 indicating the table it is in (for use with
   1840      * getTableStringBlock() and getTableCookie()) and fills in 'outValue'.  If
   1841      * not found, returns a negative error code.
   1842      *
   1843      * Note that this function does not do reference traversal.  If you want
   1844      * to follow references to other resources to get the "real" value to
   1845      * use, you need to call resolveReference() after this function.
   1846      *
   1847      * @param resID The desired resoruce identifier.
   1848      * @param outValue Filled in with the resource data that was found.
   1849      *
   1850      * @return ssize_t Either a >= 0 table index or a negative error code.
   1851      */
   1852     ssize_t getResource(uint32_t resID, Res_value* outValue, bool mayBeBag = false,
   1853                     uint16_t density = 0,
   1854                     uint32_t* outSpecFlags = NULL,
   1855                     ResTable_config* outConfig = NULL) const;
   1856 
   1857     inline ssize_t getResource(const ResTable_ref& res, Res_value* outValue,
   1858             uint32_t* outSpecFlags=NULL) const {
   1859         return getResource(res.ident, outValue, false, 0, outSpecFlags, NULL);
   1860     }
   1861 
   1862     ssize_t resolveReference(Res_value* inOutValue,
   1863                              ssize_t blockIndex,
   1864                              uint32_t* outLastRef = NULL,
   1865                              uint32_t* inoutTypeSpecFlags = NULL,
   1866                              ResTable_config* outConfig = NULL) const;
   1867 
   1868     enum {
   1869         TMP_BUFFER_SIZE = 16
   1870     };
   1871     const char16_t* valueToString(const Res_value* value, size_t stringBlock,
   1872                                   char16_t tmpBuffer[TMP_BUFFER_SIZE],
   1873                                   size_t* outLen);
   1874 
   1875     struct bag_entry {
   1876         ssize_t stringBlock;
   1877         ResTable_map map;
   1878     };
   1879 
   1880     /**
   1881      * Retrieve the bag of a resource.  If the resoruce is found, returns the
   1882      * number of bags it contains and 'outBag' points to an array of their
   1883      * values.  If not found, a negative error code is returned.
   1884      *
   1885      * Note that this function -does- do reference traversal of the bag data.
   1886      *
   1887      * @param resID The desired resource identifier.
   1888      * @param outBag Filled inm with a pointer to the bag mappings.
   1889      *
   1890      * @return ssize_t Either a >= 0 bag count of negative error code.
   1891      */
   1892     ssize_t lockBag(uint32_t resID, const bag_entry** outBag) const;
   1893 
   1894     void unlockBag(const bag_entry* bag) const;
   1895 
   1896     void lock() const;
   1897 
   1898     ssize_t getBagLocked(uint32_t resID, const bag_entry** outBag,
   1899             uint32_t* outTypeSpecFlags=NULL) const;
   1900 
   1901     void unlock() const;
   1902 
   1903     class Theme {
   1904     public:
   1905         Theme(const ResTable& table);
   1906         ~Theme();
   1907 
   1908         inline const ResTable& getResTable() const { return mTable; }
   1909 
   1910         status_t applyStyle(uint32_t resID, bool force=false);
   1911         status_t setTo(const Theme& other);
   1912 
   1913         /**
   1914          * Retrieve a value in the theme.  If the theme defines this
   1915          * value, returns a value >= 0 indicating the table it is in
   1916          * (for use with getTableStringBlock() and getTableCookie) and
   1917          * fills in 'outValue'.  If not found, returns a negative error
   1918          * code.
   1919          *
   1920          * Note that this function does not do reference traversal.  If you want
   1921          * to follow references to other resources to get the "real" value to
   1922          * use, you need to call resolveReference() after this function.
   1923          *
   1924          * @param resID A resource identifier naming the desired theme
   1925          *              attribute.
   1926          * @param outValue Filled in with the theme value that was
   1927          *                 found.
   1928          *
   1929          * @return ssize_t Either a >= 0 table index or a negative error code.
   1930          */
   1931         ssize_t getAttribute(uint32_t resID, Res_value* outValue,
   1932                 uint32_t* outTypeSpecFlags = NULL) const;
   1933 
   1934         /**
   1935          * This is like ResTable::resolveReference(), but also takes
   1936          * care of resolving attribute references to the theme.
   1937          */
   1938         ssize_t resolveAttributeReference(Res_value* inOutValue,
   1939                 ssize_t blockIndex, uint32_t* outLastRef = NULL,
   1940                 uint32_t* inoutTypeSpecFlags = NULL,
   1941                 ResTable_config* inoutConfig = NULL) const;
   1942 
   1943         void dumpToLog() const;
   1944 
   1945     private:
   1946         Theme(const Theme&);
   1947         Theme& operator=(const Theme&);
   1948 
   1949         struct theme_entry {
   1950             ssize_t stringBlock;
   1951             uint32_t typeSpecFlags;
   1952             Res_value value;
   1953         };
   1954         struct type_info {
   1955             size_t numEntries;
   1956             theme_entry* entries;
   1957         };
   1958         struct package_info {
   1959             size_t numTypes;
   1960             type_info types[];
   1961         };
   1962 
   1963         void free_package(package_info* pi);
   1964         package_info* copy_package(package_info* pi);
   1965 
   1966         const ResTable& mTable;
   1967         package_info*   mPackages[Res_MAXPACKAGE];
   1968     };
   1969 
   1970     void setParameters(const ResTable_config* params);
   1971     void getParameters(ResTable_config* params) const;
   1972 
   1973     // Retrieve an identifier (which can be passed to getResource)
   1974     // for a given resource name.  The 'name' can be fully qualified
   1975     // (<package>:<type>.<basename>) or the package or type components
   1976     // can be dropped if default values are supplied here.
   1977     //
   1978     // Returns 0 if no such resource was found, else a valid resource ID.
   1979     uint32_t identifierForName(const char16_t* name, size_t nameLen,
   1980                                const char16_t* type = 0, size_t typeLen = 0,
   1981                                const char16_t* defPackage = 0,
   1982                                size_t defPackageLen = 0,
   1983                                uint32_t* outTypeSpecFlags = NULL) const;
   1984 
   1985     static bool expandResourceRef(const uint16_t* refStr, size_t refLen,
   1986                                   String16* outPackage,
   1987                                   String16* outType,
   1988                                   String16* outName,
   1989                                   const String16* defType = NULL,
   1990                                   const String16* defPackage = NULL,
   1991                                   const char** outErrorMsg = NULL,
   1992                                   bool* outPublicOnly = NULL);
   1993 
   1994     static bool stringToInt(const char16_t* s, size_t len, Res_value* outValue);
   1995     static bool stringToFloat(const char16_t* s, size_t len, Res_value* outValue);
   1996 
   1997     // Used with stringToValue.
   1998     class Accessor
   1999     {
   2000     public:
   2001         inline virtual ~Accessor() { }
   2002 
   2003         virtual uint32_t getCustomResource(const String16& package,
   2004                                            const String16& type,
   2005                                            const String16& name) const = 0;
   2006         virtual uint32_t getCustomResourceWithCreation(const String16& package,
   2007                                                        const String16& type,
   2008                                                        const String16& name,
   2009                                                        const bool createIfNeeded = false) = 0;
   2010         virtual uint32_t getRemappedPackage(uint32_t origPackage) const = 0;
   2011         virtual bool getAttributeType(uint32_t attrID, uint32_t* outType) = 0;
   2012         virtual bool getAttributeMin(uint32_t attrID, uint32_t* outMin) = 0;
   2013         virtual bool getAttributeMax(uint32_t attrID, uint32_t* outMax) = 0;
   2014         virtual bool getAttributeEnum(uint32_t attrID,
   2015                                       const char16_t* name, size_t nameLen,
   2016                                       Res_value* outValue) = 0;
   2017         virtual bool getAttributeFlags(uint32_t attrID,
   2018                                        const char16_t* name, size_t nameLen,
   2019                                        Res_value* outValue) = 0;
   2020         virtual uint32_t getAttributeL10N(uint32_t attrID) = 0;
   2021         virtual bool getLocalizationSetting() = 0;
   2022         virtual void reportError(void* accessorCookie, const char* fmt, ...) = 0;
   2023     };
   2024 
   2025     // Convert a string to a resource value.  Handles standard "@res",
   2026     // "#color", "123", and "0x1bd" types; performs escaping of strings.
   2027     // The resulting value is placed in 'outValue'; if it is a string type,
   2028     // 'outString' receives the string.  If 'attrID' is supplied, the value is
   2029     // type checked against this attribute and it is used to perform enum
   2030     // evaluation.  If 'acccessor' is supplied, it will be used to attempt to
   2031     // resolve resources that do not exist in this ResTable.  If 'attrType' is
   2032     // supplied, the value will be type checked for this format if 'attrID'
   2033     // is not supplied or found.
   2034     bool stringToValue(Res_value* outValue, String16* outString,
   2035                        const char16_t* s, size_t len,
   2036                        bool preserveSpaces, bool coerceType,
   2037                        uint32_t attrID = 0,
   2038                        const String16* defType = NULL,
   2039                        const String16* defPackage = NULL,
   2040                        Accessor* accessor = NULL,
   2041                        void* accessorCookie = NULL,
   2042                        uint32_t attrType = ResTable_map::TYPE_ANY,
   2043                        bool enforcePrivate = true) const;
   2044 
   2045     // Perform processing of escapes and quotes in a string.
   2046     static bool collectString(String16* outString,
   2047                               const char16_t* s, size_t len,
   2048                               bool preserveSpaces,
   2049                               const char** outErrorMsg = NULL,
   2050                               bool append = false);
   2051 
   2052     size_t getBasePackageCount() const;
   2053     const char16_t* getBasePackageName(size_t idx) const;
   2054     uint32_t getBasePackageId(size_t idx) const;
   2055 
   2056     size_t getTableCount() const;
   2057     const ResStringPool* getTableStringBlock(size_t index) const;
   2058     void* getTableCookie(size_t index) const;
   2059 
   2060     // Return the configurations (ResTable_config) that we know about
   2061     void getConfigurations(Vector<ResTable_config>* configs) const;
   2062 
   2063     void getLocales(Vector<String8>* locales) const;
   2064 
   2065     // Generate an idmap.
   2066     //
   2067     // Return value: on success: NO_ERROR; caller is responsible for free-ing
   2068     // outData (using free(3)). On failure, any status_t value other than
   2069     // NO_ERROR; the caller should not free outData.
   2070     status_t createIdmap(const ResTable& overlay, uint32_t originalCrc, uint32_t overlayCrc,
   2071                          void** outData, size_t* outSize) const;
   2072 
   2073     enum {
   2074         IDMAP_HEADER_SIZE_BYTES = 3 * sizeof(uint32_t),
   2075     };
   2076     // Retrieve idmap meta-data.
   2077     //
   2078     // This function only requires the idmap header (the first
   2079     // IDMAP_HEADER_SIZE_BYTES) bytes of an idmap file.
   2080     static bool getIdmapInfo(const void* idmap, size_t size,
   2081                              uint32_t* pOriginalCrc, uint32_t* pOverlayCrc);
   2082 
   2083 #ifndef HAVE_ANDROID_OS
   2084     void print(bool inclValues) const;
   2085     static String8 normalizeForOutput(const char* input);
   2086 #endif
   2087 
   2088 private:
   2089     struct Header;
   2090     struct Type;
   2091     struct Package;
   2092     struct PackageGroup;
   2093     struct bag_set;
   2094 
   2095     status_t add(const void* data, size_t size, void* cookie,
   2096                  Asset* asset, bool copyData, const Asset* idmap);
   2097 
   2098     ssize_t getResourcePackageIndex(uint32_t resID) const;
   2099     ssize_t getEntry(
   2100         const Package* package, int typeIndex, int entryIndex,
   2101         const ResTable_config* config,
   2102         const ResTable_type** outType, const ResTable_entry** outEntry,
   2103         const Type** outTypeClass) const;
   2104     status_t parsePackage(
   2105         const ResTable_package* const pkg, const Header* const header, uint32_t idmap_id);
   2106 
   2107     void print_value(const Package* pkg, const Res_value& value) const;
   2108 
   2109     mutable Mutex               mLock;
   2110 
   2111     status_t                    mError;
   2112 
   2113     ResTable_config             mParams;
   2114 
   2115     // Array of all resource tables.
   2116     Vector<Header*>             mHeaders;
   2117 
   2118     // Array of packages in all resource tables.
   2119     Vector<PackageGroup*>       mPackageGroups;
   2120 
   2121     // Mapping from resource package IDs to indices into the internal
   2122     // package array.
   2123     uint8_t                     mPackageMap[256];
   2124 };
   2125 
   2126 }   // namespace android
   2127 
   2128 #endif // _LIBS_UTILS_RESOURCE_TYPES_H
   2129