summaryrefslogtreecommitdiffstats
path: root/include
diff options
context:
space:
mode:
Diffstat (limited to 'include')
-rw-r--r--include/binder/BinderService.h8
-rw-r--r--include/binder/IPCThreadState.h2
-rw-r--r--include/binder/IServiceManager.h3
-rw-r--r--include/gui/BitTube.h (renamed from include/gui/SensorChannel.h)9
-rw-r--r--include/gui/BufferQueue.h345
-rw-r--r--include/gui/DisplayEventReceiver.h123
-rw-r--r--include/gui/IDisplayEventConnection.h73
-rw-r--r--include/gui/ISensorEventConnection.h4
-rw-r--r--include/gui/SensorEventQueue.h4
-rw-r--r--include/gui/SurfaceTexture.h298
-rw-r--r--include/private/gui/ComposerService.h53
-rw-r--r--include/surfaceflinger/ISurfaceComposer.h10
-rw-r--r--include/surfaceflinger/SurfaceComposerClient.h22
-rw-r--r--include/ui/GraphicLog.h70
-rw-r--r--include/ui/Input.h897
-rw-r--r--include/ui/InputTransport.h338
-rw-r--r--include/ui/KeyCharacterMap.h199
-rw-r--r--include/ui/KeyLayoutMap.h99
-rw-r--r--include/ui/Keyboard.h119
-rwxr-xr-xinclude/ui/KeycodeLabels.h310
-rw-r--r--include/ui/PixelFormat.h12
-rw-r--r--include/ui/PowerManager.h33
-rw-r--r--include/ui/Region.h14
-rw-r--r--include/ui/VirtualKeyMap.h79
-rw-r--r--include/utils/Asset.h322
-rw-r--r--include/utils/AssetDir.h145
-rw-r--r--include/utils/AssetManager.h373
-rw-r--r--include/utils/BackupHelpers.h169
-rw-r--r--include/utils/BasicHashtable.h393
-rw-r--r--include/utils/CallStack.h8
-rw-r--r--include/utils/GenerationCache.h114
-rw-r--r--include/utils/KeyedVector.h2
-rw-r--r--include/utils/ObbFile.h145
-rw-r--r--include/utils/ResourceTypes.h2128
-rw-r--r--include/utils/StreamingZipInflater.h84
-rw-r--r--include/utils/TypeHelpers.h48
-rw-r--r--include/utils/ZipFileCRO.h61
-rw-r--r--include/utils/ZipFileRO.h262
-rw-r--r--include/utils/ZipUtils.h67
-rw-r--r--include/utils/threads.h12
40 files changed, 1144 insertions, 6313 deletions
diff --git a/include/binder/BinderService.h b/include/binder/BinderService.h
index 2316fef..ca594d3 100644
--- a/include/binder/BinderService.h
+++ b/include/binder/BinderService.h
@@ -34,15 +34,15 @@ template<typename SERVICE>
class BinderService
{
public:
- static status_t publish() {
+ static status_t publish(bool allowIsolated = false) {
sp<IServiceManager> sm(defaultServiceManager());
- return sm->addService(String16(SERVICE::getServiceName()), new SERVICE());
+ return sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);
}
- static void publishAndJoinThreadPool() {
+ static void publishAndJoinThreadPool(bool allowIsolated = false) {
sp<ProcessState> proc(ProcessState::self());
sp<IServiceManager> sm(defaultServiceManager());
- sm->addService(String16(SERVICE::getServiceName()), new SERVICE());
+ sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);
ProcessState::self()->startThreadPool();
IPCThreadState::self()->joinThreadPool();
}
diff --git a/include/binder/IPCThreadState.h b/include/binder/IPCThreadState.h
index 3378d97..691ba2f 100644
--- a/include/binder/IPCThreadState.h
+++ b/include/binder/IPCThreadState.h
@@ -41,6 +41,7 @@ public:
int getCallingPid();
int getCallingUid();
+ int getOrigCallingUid();
void setStrictModePolicy(int32_t policy);
int32_t getStrictModePolicy() const;
@@ -116,6 +117,7 @@ private:
status_t mLastError;
pid_t mCallingPid;
uid_t mCallingUid;
+ uid_t mOrigCallingUid;
int32_t mStrictModePolicy;
int32_t mLastTransactionBinderFlags;
};
diff --git a/include/binder/IServiceManager.h b/include/binder/IServiceManager.h
index 24e9e99..2c297d6 100644
--- a/include/binder/IServiceManager.h
+++ b/include/binder/IServiceManager.h
@@ -47,7 +47,8 @@ public:
* Register a service.
*/
virtual status_t addService( const String16& name,
- const sp<IBinder>& service) = 0;
+ const sp<IBinder>& service,
+ bool allowIsolated = false) = 0;
/**
* Return list of all existing services.
diff --git a/include/gui/SensorChannel.h b/include/gui/BitTube.h
index bb54618..76389a0 100644
--- a/include/gui/SensorChannel.h
+++ b/include/gui/BitTube.h
@@ -28,14 +28,15 @@ namespace android {
// ----------------------------------------------------------------------------
class Parcel;
-class SensorChannel : public RefBase
+class BitTube : public RefBase
{
public:
- SensorChannel();
- SensorChannel(const Parcel& data);
- virtual ~SensorChannel();
+ BitTube();
+ BitTube(const Parcel& data);
+ virtual ~BitTube();
+ status_t initCheck() const;
int getFd() const;
ssize_t write(void const* vaddr, size_t size);
ssize_t read(void* vaddr, size_t size);
diff --git a/include/gui/BufferQueue.h b/include/gui/BufferQueue.h
new file mode 100644
index 0000000..ae99160
--- /dev/null
+++ b/include/gui/BufferQueue.h
@@ -0,0 +1,345 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_GUI_BUFFERQUEUE_H
+#define ANDROID_GUI_BUFFERQUEUE_H
+
+#include <EGL/egl.h>
+
+#include <gui/ISurfaceTexture.h>
+
+#include <surfaceflinger/IGraphicBufferAlloc.h>
+#include <ui/GraphicBuffer.h>
+
+#include <utils/String8.h>
+#include <utils/Vector.h>
+#include <utils/threads.h>
+
+namespace android {
+// ----------------------------------------------------------------------------
+
+class BufferQueue : public BnSurfaceTexture {
+public:
+ enum { MIN_UNDEQUEUED_BUFFERS = 2 };
+ enum {
+ MIN_ASYNC_BUFFER_SLOTS = MIN_UNDEQUEUED_BUFFERS + 1,
+ MIN_SYNC_BUFFER_SLOTS = MIN_UNDEQUEUED_BUFFERS
+ };
+ enum { NUM_BUFFER_SLOTS = 32 };
+ enum { NO_CONNECTED_API = 0 };
+
+ struct FrameAvailableListener : public virtual RefBase {
+ // onFrameAvailable() is called from queueBuffer() each time an
+ // additional frame becomes available for consumption. This means that
+ // frames that are queued while in asynchronous mode only trigger the
+ // callback if no previous frames are pending. Frames queued while in
+ // synchronous mode always trigger the callback.
+ //
+ // This is called without any lock held and can be called concurrently
+ // by multiple threads.
+ virtual void onFrameAvailable() = 0;
+ };
+
+ // BufferQueue manages a pool of gralloc memory slots to be used
+ // by producers and consumers.
+ // allowSynchronousMode specifies whether or not synchronous mode can be
+ // enabled.
+ BufferQueue(bool allowSynchronousMode = true);
+ virtual ~BufferQueue();
+
+ virtual int query(int what, int* value);
+
+ // setBufferCount updates the number of available buffer slots. After
+ // calling this all buffer slots are both unallocated and owned by the
+ // BufferQueue object (i.e. they are not owned by the client).
+ virtual status_t setBufferCount(int bufferCount);
+
+ virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf);
+
+ // dequeueBuffer gets the next buffer slot index for the client to use. If a
+ // buffer slot is available then that slot index is written to the location
+ // pointed to by the buf argument and a status of OK is returned. If no
+ // slot is available then a status of -EBUSY is returned and buf is
+ // unmodified.
+ // The width and height parameters must be no greater than the minimum of
+ // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
+ // An error due to invalid dimensions might not be reported until
+ // updateTexImage() is called.
+ virtual status_t dequeueBuffer(int *buf, uint32_t width, uint32_t height,
+ uint32_t format, uint32_t usage);
+
+ // queueBuffer returns a filled buffer to the BufferQueue. In addition, a
+ // timestamp must be provided for the buffer. The timestamp is in
+ // nanoseconds, and must be monotonically increasing. Its other semantics
+ // (zero point, etc) are client-dependent and should be documented by the
+ // client.
+ virtual status_t queueBuffer(int buf, int64_t timestamp,
+ uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform);
+ virtual void cancelBuffer(int buf);
+ virtual status_t setCrop(const Rect& reg);
+ virtual status_t setTransform(uint32_t transform);
+ virtual status_t setScalingMode(int mode);
+
+ // setSynchronousMode set whether dequeueBuffer is synchronous or
+ // asynchronous. In synchronous mode, dequeueBuffer blocks until
+ // a buffer is available, the currently bound buffer can be dequeued and
+ // queued buffers will be retired in order.
+ // The default mode is asynchronous.
+ virtual status_t setSynchronousMode(bool enabled);
+
+ // connect attempts to connect a producer client API to the BufferQueue.
+ // This must be called before any other ISurfaceTexture methods are called
+ // except for getAllocator.
+ //
+ // This method will fail if the connect was previously called on the
+ // BufferQueue and no corresponding disconnect call was made.
+ virtual status_t connect(int api,
+ uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform);
+
+ // disconnect attempts to disconnect a producer client API from the
+ // BufferQueue. Calling this method will cause any subsequent calls to other
+ // ISurfaceTexture methods to fail except for getAllocator and connect.
+ // Successfully calling connect after this will allow the other methods to
+ // succeed again.
+ //
+ // This method will fail if the the BufferQueue is not currently
+ // connected to the specified client API.
+ virtual status_t disconnect(int api);
+
+protected:
+
+ // freeBufferLocked frees the resources (both GraphicBuffer and EGLImage)
+ // for the given slot.
+ void freeBufferLocked(int index);
+
+ // freeAllBuffersLocked frees the resources (both GraphicBuffer and
+ // EGLImage) for all slots.
+ void freeAllBuffersLocked();
+
+ // freeAllBuffersExceptHeadLocked frees the resources (both GraphicBuffer
+ // and EGLImage) for all slots except the head of mQueue
+ void freeAllBuffersExceptHeadLocked();
+
+ // drainQueueLocked drains the buffer queue if we're in synchronous mode
+ // returns immediately otherwise. It returns NO_INIT if the BufferQueue
+ // became abandoned or disconnected during this call.
+ status_t drainQueueLocked();
+
+ // drainQueueAndFreeBuffersLocked drains the buffer queue if we're in
+ // synchronous mode and free all buffers. In asynchronous mode, all buffers
+ // are freed except the current buffer.
+ status_t drainQueueAndFreeBuffersLocked();
+
+ status_t setBufferCountServerLocked(int bufferCount);
+
+ enum { INVALID_BUFFER_SLOT = -1 };
+
+ struct BufferSlot {
+
+ BufferSlot()
+ : mEglImage(EGL_NO_IMAGE_KHR),
+ mEglDisplay(EGL_NO_DISPLAY),
+ mBufferState(BufferSlot::FREE),
+ mRequestBufferCalled(false),
+ mTransform(0),
+ mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
+ mTimestamp(0),
+ mFrameNumber(0),
+ mFence(EGL_NO_SYNC_KHR) {
+ mCrop.makeInvalid();
+ }
+
+ // mGraphicBuffer points to the buffer allocated for this slot or is NULL
+ // if no buffer has been allocated.
+ sp<GraphicBuffer> mGraphicBuffer;
+
+ // mEglImage is the EGLImage created from mGraphicBuffer.
+ EGLImageKHR mEglImage;
+
+ // mEglDisplay is the EGLDisplay used to create mEglImage.
+ EGLDisplay mEglDisplay;
+
+ // BufferState represents the different states in which a buffer slot
+ // can be.
+ enum BufferState {
+ // FREE indicates that the buffer is not currently being used and
+ // will not be used in the future until it gets dequeued and
+ // subsequently queued by the client.
+ FREE = 0,
+
+ // DEQUEUED indicates that the buffer has been dequeued by the
+ // client, but has not yet been queued or canceled. The buffer is
+ // considered 'owned' by the client, and the server should not use
+ // it for anything.
+ //
+ // Note that when in synchronous-mode (mSynchronousMode == true),
+ // the buffer that's currently attached to the texture may be
+ // dequeued by the client. That means that the current buffer can
+ // be in either the DEQUEUED or QUEUED state. In asynchronous mode,
+ // however, the current buffer is always in the QUEUED state.
+ DEQUEUED = 1,
+
+ // QUEUED indicates that the buffer has been queued by the client,
+ // and has not since been made available for the client to dequeue.
+ // Attaching the buffer to the texture does NOT transition the
+ // buffer away from the QUEUED state. However, in Synchronous mode
+ // the current buffer may be dequeued by the client under some
+ // circumstances. See the note about the current buffer in the
+ // documentation for DEQUEUED.
+ QUEUED = 2,
+ };
+
+ // mBufferState is the current state of this buffer slot.
+ BufferState mBufferState;
+
+ // mRequestBufferCalled is used for validating that the client did
+ // call requestBuffer() when told to do so. Technically this is not
+ // needed but useful for debugging and catching client bugs.
+ bool mRequestBufferCalled;
+
+ // mCrop is the current crop rectangle for this buffer slot. This gets
+ // set to mNextCrop each time queueBuffer gets called for this buffer.
+ Rect mCrop;
+
+ // mTransform is the current transform flags for this buffer slot. This
+ // gets set to mNextTransform each time queueBuffer gets called for this
+ // slot.
+ uint32_t mTransform;
+
+ // mScalingMode is the current scaling mode for this buffer slot. This
+ // gets set to mNextScalingMode each time queueBuffer gets called for
+ // this slot.
+ uint32_t mScalingMode;
+
+ // mTimestamp is the current timestamp for this buffer slot. This gets
+ // to set by queueBuffer each time this slot is queued.
+ int64_t mTimestamp;
+
+ // mFrameNumber is the number of the queued frame for this slot.
+ uint64_t mFrameNumber;
+
+ // mFence is the EGL sync object that must signal before the buffer
+ // associated with this buffer slot may be dequeued. It is initialized
+ // to EGL_NO_SYNC_KHR when the buffer is created and (optionally, based
+ // on a compile-time option) set to a new sync object in updateTexImage.
+ EGLSyncKHR mFence;
+ };
+
+ // mSlots is the array of buffer slots that must be mirrored on the client
+ // side. This allows buffer ownership to be transferred between the client
+ // and server without sending a GraphicBuffer over binder. The entire array
+ // is initialized to NULL at construction time, and buffers are allocated
+ // for a slot when requestBuffer is called with that slot's index.
+ BufferSlot mSlots[NUM_BUFFER_SLOTS];
+
+
+ // mDefaultWidth holds the default width of allocated buffers. It is used
+ // in requestBuffers() if a width and height of zero is specified.
+ uint32_t mDefaultWidth;
+
+ // mDefaultHeight holds the default height of allocated buffers. It is used
+ // in requestBuffers() if a width and height of zero is specified.
+ uint32_t mDefaultHeight;
+
+ // mPixelFormat holds the pixel format of allocated buffers. It is used
+ // in requestBuffers() if a format of zero is specified.
+ uint32_t mPixelFormat;
+
+ // mBufferCount is the number of buffer slots that the client and server
+ // must maintain. It defaults to MIN_ASYNC_BUFFER_SLOTS and can be changed
+ // by calling setBufferCount or setBufferCountServer
+ int mBufferCount;
+
+ // mClientBufferCount is the number of buffer slots requested by the client.
+ // The default is zero, which means the client doesn't care how many buffers
+ // there is.
+ int mClientBufferCount;
+
+ // mServerBufferCount buffer count requested by the server-side
+ int mServerBufferCount;
+
+ // mCurrentTexture is the buffer slot index of the buffer that is currently
+ // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
+ // indicating that no buffer slot is currently bound to the texture. Note,
+ // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
+ // that no buffer is bound to the texture. A call to setBufferCount will
+ // reset mCurrentTexture to INVALID_BUFFER_SLOT.
+ int mCurrentTexture;
+
+ // mNextCrop is the crop rectangle that will be used for the next buffer
+ // that gets queued. It is set by calling setCrop.
+ Rect mNextCrop;
+
+ // mNextTransform is the transform identifier that will be used for the next
+ // buffer that gets queued. It is set by calling setTransform.
+ uint32_t mNextTransform;
+
+ // mNextScalingMode is the scaling mode that will be used for the next
+ // buffers that get queued. It is set by calling setScalingMode.
+ int mNextScalingMode;
+
+ // mGraphicBufferAlloc is the connection to SurfaceFlinger that is used to
+ // allocate new GraphicBuffer objects.
+ sp<IGraphicBufferAlloc> mGraphicBufferAlloc;
+
+ // mFrameAvailableListener is the listener object that will be called when a
+ // new frame becomes available. If it is not NULL it will be called from
+ // queueBuffer.
+ sp<FrameAvailableListener> mFrameAvailableListener;
+
+ // mSynchronousMode whether we're in synchronous mode or not
+ bool mSynchronousMode;
+
+ // mAllowSynchronousMode whether we allow synchronous mode or not
+ const bool mAllowSynchronousMode;
+
+ // mConnectedApi indicates the API that is currently connected to this
+ // BufferQueue. It defaults to NO_CONNECTED_API (= 0), and gets updated
+ // by the connect and disconnect methods.
+ int mConnectedApi;
+
+ // mDequeueCondition condition used for dequeueBuffer in synchronous mode
+ mutable Condition mDequeueCondition;
+
+ // mQueue is a FIFO of queued buffers used in synchronous mode
+ typedef Vector<int> Fifo;
+ Fifo mQueue;
+
+ // mAbandoned indicates that the BufferQueue will no longer be used to
+ // consume images buffers pushed to it using the ISurfaceTexture interface.
+ // It is initialized to false, and set to true in the abandon method. A
+ // BufferQueue that has been abandoned will return the NO_INIT error from
+ // all ISurfaceTexture methods capable of returning an error.
+ bool mAbandoned;
+
+ // mName is a string used to identify the BufferQueue in log messages.
+ // It is set by the setName method.
+ String8 mName;
+
+ // mMutex is the mutex used to prevent concurrent access to the member
+ // variables of BufferQueue objects. It must be locked whenever the
+ // member variables are accessed.
+ mutable Mutex mMutex;
+
+ // mFrameCounter is the free running counter, incremented for every buffer queued
+ // with the surface Texture.
+ uint64_t mFrameCounter;
+};
+
+// ----------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_GUI_BUFFERQUEUE_H
diff --git a/include/gui/DisplayEventReceiver.h b/include/gui/DisplayEventReceiver.h
new file mode 100644
index 0000000..7bca8d6
--- /dev/null
+++ b/include/gui/DisplayEventReceiver.h
@@ -0,0 +1,123 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_GUI_DISPLAY_EVENT_H
+#define ANDROID_GUI_DISPLAY_EVENT_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Errors.h>
+#include <utils/RefBase.h>
+#include <utils/Timers.h>
+
+#include <binder/IInterface.h>
+
+// ----------------------------------------------------------------------------
+
+namespace android {
+
+// ----------------------------------------------------------------------------
+
+class BitTube;
+class IDisplayEventConnection;
+
+// ----------------------------------------------------------------------------
+
+class DisplayEventReceiver {
+public:
+ enum {
+ DISPLAY_EVENT_VSYNC = 'vsyn'
+ };
+
+ struct Event {
+
+ struct Header {
+ uint32_t type;
+ nsecs_t timestamp;
+ };
+
+ struct VSync {
+ uint32_t count;
+ };
+
+ Header header;
+ union {
+ VSync vsync;
+ };
+ };
+
+public:
+ /*
+ * DisplayEventReceiver creates and registers an event connection with
+ * SurfaceFlinger. VSync events are disabled by default. Call setVSyncRate
+ * or requestNextVsync to receive them.
+ * Other events start being delivered immediately.
+ */
+ DisplayEventReceiver();
+
+ /*
+ * ~DisplayEventReceiver severs the connection with SurfaceFlinger, new events
+ * stop being delivered immediately. Note that the queue could have
+ * some events pending. These will be delivered.
+ */
+ ~DisplayEventReceiver();
+
+ /*
+ * initCheck returns the state of DisplayEventReceiver after construction.
+ */
+ status_t initCheck() const;
+
+ /*
+ * getFd returns the file descriptor to use to receive events.
+ * OWNERSHIP IS RETAINED by DisplayEventReceiver. DO NOT CLOSE this
+ * file-descriptor.
+ */
+ int getFd() const;
+
+ /*
+ * getEvents reads event from the queue and returns how many events were
+ * read. Returns 0 if there are no more events or a negative error code.
+ * If NOT_ENOUGH_DATA is returned, the object has become invalid forever, it
+ * should be destroyed and getEvents() shouldn't be called again.
+ */
+ ssize_t getEvents(Event* events, size_t count);
+ static ssize_t getEvents(const sp<BitTube>& dataChannel,
+ Event* events, size_t count);
+
+ /*
+ * setVsyncRate() sets the Event::VSync delivery rate. A value of
+ * 1 returns every Event::VSync. A value of 2 returns every other event,
+ * etc... a value of 0 returns no event unless requestNextVsync() has
+ * been called.
+ */
+ status_t setVsyncRate(uint32_t count);
+
+ /*
+ * requestNextVsync() schedules the next Event::VSync. It has no effect
+ * if the vsync rate is > 0.
+ */
+ status_t requestNextVsync();
+
+private:
+ sp<IDisplayEventConnection> mEventConnection;
+ sp<BitTube> mDataChannel;
+};
+
+// ----------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_GUI_DISPLAY_EVENT_H
diff --git a/include/gui/IDisplayEventConnection.h b/include/gui/IDisplayEventConnection.h
new file mode 100644
index 0000000..86247de
--- /dev/null
+++ b/include/gui/IDisplayEventConnection.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_GUI_IDISPLAY_EVENT_CONNECTION_H
+#define ANDROID_GUI_IDISPLAY_EVENT_CONNECTION_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Errors.h>
+#include <utils/RefBase.h>
+
+#include <binder/IInterface.h>
+
+namespace android {
+// ----------------------------------------------------------------------------
+
+class BitTube;
+
+class IDisplayEventConnection : public IInterface
+{
+public:
+
+ DECLARE_META_INTERFACE(DisplayEventConnection);
+
+ /*
+ * getDataChannel() returns a BitTube where to receive the events from
+ */
+ virtual sp<BitTube> getDataChannel() const = 0;
+
+ /*
+ * setVsyncRate() sets the vsync event delivery rate. A value of
+ * 1 returns every vsync events. A value of 2 returns every other events,
+ * etc... a value of 0 returns no event unless requestNextVsync() has
+ * been called.
+ */
+ virtual void setVsyncRate(uint32_t count) = 0;
+
+ /*
+ * requestNextVsync() schedules the next vsync event. It has no effect
+ * if the vsync rate is > 0.
+ */
+ virtual void requestNextVsync() = 0; // asynchronous
+};
+
+// ----------------------------------------------------------------------------
+
+class BnDisplayEventConnection : public BnInterface<IDisplayEventConnection>
+{
+public:
+ virtual status_t onTransact( uint32_t code,
+ const Parcel& data,
+ Parcel* reply,
+ uint32_t flags = 0);
+};
+
+// ----------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_GUI_IDISPLAY_EVENT_CONNECTION_H
diff --git a/include/gui/ISensorEventConnection.h b/include/gui/ISensorEventConnection.h
index ed4e4cc..749065e 100644
--- a/include/gui/ISensorEventConnection.h
+++ b/include/gui/ISensorEventConnection.h
@@ -28,14 +28,14 @@
namespace android {
// ----------------------------------------------------------------------------
-class SensorChannel;
+class BitTube;
class ISensorEventConnection : public IInterface
{
public:
DECLARE_META_INTERFACE(SensorEventConnection);
- virtual sp<SensorChannel> getSensorChannel() const = 0;
+ virtual sp<BitTube> getSensorChannel() const = 0;
virtual status_t enableDisable(int handle, bool enabled) = 0;
virtual status_t setEventRate(int handle, nsecs_t ns) = 0;
};
diff --git a/include/gui/SensorEventQueue.h b/include/gui/SensorEventQueue.h
index 97dd391..ef7c6e3 100644
--- a/include/gui/SensorEventQueue.h
+++ b/include/gui/SensorEventQueue.h
@@ -24,7 +24,7 @@
#include <utils/RefBase.h>
#include <utils/Timers.h>
-#include <gui/SensorChannel.h>
+#include <gui/BitTube.h>
// ----------------------------------------------------------------------------
@@ -71,7 +71,7 @@ public:
private:
sp<Looper> getLooper() const;
sp<ISensorEventConnection> mSensorEventConnection;
- sp<SensorChannel> mSensorChannel;
+ sp<BitTube> mSensorChannel;
mutable Mutex mLock;
mutable sp<Looper> mLooper;
};
diff --git a/include/gui/SurfaceTexture.h b/include/gui/SurfaceTexture.h
index a8c7672..dcab049 100644
--- a/include/gui/SurfaceTexture.h
+++ b/include/gui/SurfaceTexture.h
@@ -23,6 +23,7 @@
#include <GLES2/gl2ext.h>
#include <gui/ISurfaceTexture.h>
+#include <gui/BufferQueue.h>
#include <ui/GraphicBuffer.h>
@@ -35,30 +36,11 @@
namespace android {
// ----------------------------------------------------------------------------
-class IGraphicBufferAlloc;
+
class String8;
-class SurfaceTexture : public BnSurfaceTexture {
+class SurfaceTexture : public BufferQueue {
public:
- enum { MIN_UNDEQUEUED_BUFFERS = 2 };
- enum {
- MIN_ASYNC_BUFFER_SLOTS = MIN_UNDEQUEUED_BUFFERS + 1,
- MIN_SYNC_BUFFER_SLOTS = MIN_UNDEQUEUED_BUFFERS
- };
- enum { NUM_BUFFER_SLOTS = 32 };
- enum { NO_CONNECTED_API = 0 };
-
- struct FrameAvailableListener : public virtual RefBase {
- // onFrameAvailable() is called from queueBuffer() each time an
- // additional frame becomes available for consumption. This means that
- // frames that are queued while in asynchronous mode only trigger the
- // callback if no previous frames are pending. Frames queued while in
- // synchronous mode always trigger the callback.
- //
- // This is called without any lock held and can be called concurrently
- // by multiple threads.
- virtual void onFrameAvailable() = 0;
- };
// SurfaceTexture constructs a new SurfaceTexture object. tex indicates the
// name of the OpenGL ES texture to which images are to be streamed. This
@@ -73,64 +55,7 @@ public:
virtual ~SurfaceTexture();
- // setBufferCount updates the number of available buffer slots. After
- // calling this all buffer slots are both unallocated and owned by the
- // SurfaceTexture object (i.e. they are not owned by the client).
- virtual status_t setBufferCount(int bufferCount);
-
- virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf);
- // dequeueBuffer gets the next buffer slot index for the client to use. If a
- // buffer slot is available then that slot index is written to the location
- // pointed to by the buf argument and a status of OK is returned. If no
- // slot is available then a status of -EBUSY is returned and buf is
- // unmodified.
- // The width and height parameters must be no greater than the minimum of
- // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
- // An error due to invalid dimensions might not be reported until
- // updateTexImage() is called.
- virtual status_t dequeueBuffer(int *buf, uint32_t width, uint32_t height,
- uint32_t format, uint32_t usage);
-
- // queueBuffer returns a filled buffer to the SurfaceTexture. In addition, a
- // timestamp must be provided for the buffer. The timestamp is in
- // nanoseconds, and must be monotonically increasing. Its other semantics
- // (zero point, etc) are client-dependent and should be documented by the
- // client.
- virtual status_t queueBuffer(int buf, int64_t timestamp,
- uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform);
- virtual void cancelBuffer(int buf);
- virtual status_t setCrop(const Rect& reg);
- virtual status_t setTransform(uint32_t transform);
- virtual status_t setScalingMode(int mode);
-
- virtual int query(int what, int* value);
-
- // setSynchronousMode set whether dequeueBuffer is synchronous or
- // asynchronous. In synchronous mode, dequeueBuffer blocks until
- // a buffer is available, the currently bound buffer can be dequeued and
- // queued buffers will be retired in order.
- // The default mode is asynchronous.
- virtual status_t setSynchronousMode(bool enabled);
-
- // connect attempts to connect a client API to the SurfaceTexture. This
- // must be called before any other ISurfaceTexture methods are called except
- // for getAllocator.
- //
- // This method will fail if the connect was previously called on the
- // SurfaceTexture and no corresponding disconnect call was made.
- virtual status_t connect(int api,
- uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform);
-
- // disconnect attempts to disconnect a client API from the SurfaceTexture.
- // Calling this method will cause any subsequent calls to other
- // ISurfaceTexture methods to fail except for getAllocator and connect.
- // Successfully calling connect after this will allow the other methods to
- // succeed again.
- //
- // This method will fail if the the SurfaceTexture is not currently
- // connected to the specified client API.
- virtual status_t disconnect(int api);
// updateTexImage sets the image contents of the target texture to that of
// the most recently queued buffer.
@@ -233,28 +158,6 @@ public:
protected:
- // freeBufferLocked frees the resources (both GraphicBuffer and EGLImage)
- // for the given slot.
- void freeBufferLocked(int index);
-
- // freeAllBuffersLocked frees the resources (both GraphicBuffer and
- // EGLImage) for all slots.
- void freeAllBuffersLocked();
-
- // freeAllBuffersExceptHeadLocked frees the resources (both GraphicBuffer
- // and EGLImage) for all slots except the head of mQueue
- void freeAllBuffersExceptHeadLocked();
-
- // drainQueueLocked drains the buffer queue if we're in synchronous mode
- // returns immediately otherwise. return NO_INIT if SurfaceTexture
- // became abandoned or disconnected during this call.
- status_t drainQueueLocked();
-
- // drainQueueAndFreeBuffersLocked drains the buffer queue if we're in
- // synchronous mode and free all buffers. In asynchronous mode, all buffers
- // are freed except the current buffer.
- status_t drainQueueAndFreeBuffersLocked();
-
static bool isExternalFormat(uint32_t format);
private:
@@ -263,146 +166,11 @@ private:
EGLImageKHR createImage(EGLDisplay dpy,
const sp<GraphicBuffer>& graphicBuffer);
- status_t setBufferCountServerLocked(int bufferCount);
-
// computeCurrentTransformMatrix computes the transform matrix for the
// current texture. It uses mCurrentTransform and the current GraphicBuffer
// to compute this matrix and stores it in mCurrentTransformMatrix.
void computeCurrentTransformMatrix();
- enum { INVALID_BUFFER_SLOT = -1 };
-
- struct BufferSlot {
-
- BufferSlot()
- : mEglImage(EGL_NO_IMAGE_KHR),
- mEglDisplay(EGL_NO_DISPLAY),
- mBufferState(BufferSlot::FREE),
- mRequestBufferCalled(false),
- mTransform(0),
- mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
- mTimestamp(0),
- mFrameNumber(0),
- mFence(EGL_NO_SYNC_KHR) {
- mCrop.makeInvalid();
- }
-
- // mGraphicBuffer points to the buffer allocated for this slot or is NULL
- // if no buffer has been allocated.
- sp<GraphicBuffer> mGraphicBuffer;
-
- // mEglImage is the EGLImage created from mGraphicBuffer.
- EGLImageKHR mEglImage;
-
- // mEglDisplay is the EGLDisplay used to create mEglImage.
- EGLDisplay mEglDisplay;
-
- // BufferState represents the different states in which a buffer slot
- // can be.
- enum BufferState {
- // FREE indicates that the buffer is not currently being used and
- // will not be used in the future until it gets dequeued and
- // subsequently queued by the client.
- FREE = 0,
-
- // DEQUEUED indicates that the buffer has been dequeued by the
- // client, but has not yet been queued or canceled. The buffer is
- // considered 'owned' by the client, and the server should not use
- // it for anything.
- //
- // Note that when in synchronous-mode (mSynchronousMode == true),
- // the buffer that's currently attached to the texture may be
- // dequeued by the client. That means that the current buffer can
- // be in either the DEQUEUED or QUEUED state. In asynchronous mode,
- // however, the current buffer is always in the QUEUED state.
- DEQUEUED = 1,
-
- // QUEUED indicates that the buffer has been queued by the client,
- // and has not since been made available for the client to dequeue.
- // Attaching the buffer to the texture does NOT transition the
- // buffer away from the QUEUED state. However, in Synchronous mode
- // the current buffer may be dequeued by the client under some
- // circumstances. See the note about the current buffer in the
- // documentation for DEQUEUED.
- QUEUED = 2,
- };
-
- // mBufferState is the current state of this buffer slot.
- BufferState mBufferState;
-
- // mRequestBufferCalled is used for validating that the client did
- // call requestBuffer() when told to do so. Technically this is not
- // needed but useful for debugging and catching client bugs.
- bool mRequestBufferCalled;
-
- // mCrop is the current crop rectangle for this buffer slot. This gets
- // set to mNextCrop each time queueBuffer gets called for this buffer.
- Rect mCrop;
-
- // mTransform is the current transform flags for this buffer slot. This
- // gets set to mNextTransform each time queueBuffer gets called for this
- // slot.
- uint32_t mTransform;
-
- // mScalingMode is the current scaling mode for this buffer slot. This
- // gets set to mNextScalingMode each time queueBuffer gets called for
- // this slot.
- uint32_t mScalingMode;
-
- // mTimestamp is the current timestamp for this buffer slot. This gets
- // to set by queueBuffer each time this slot is queued.
- int64_t mTimestamp;
-
- // mFrameNumber is the number of the queued frame for this slot.
- uint64_t mFrameNumber;
-
- // mFence is the EGL sync object that must signal before the buffer
- // associated with this buffer slot may be dequeued. It is initialized
- // to EGL_NO_SYNC_KHR when the buffer is created and (optionally, based
- // on a compile-time option) set to a new sync object in updateTexImage.
- EGLSyncKHR mFence;
- };
-
- // mSlots is the array of buffer slots that must be mirrored on the client
- // side. This allows buffer ownership to be transferred between the client
- // and server without sending a GraphicBuffer over binder. The entire array
- // is initialized to NULL at construction time, and buffers are allocated
- // for a slot when requestBuffer is called with that slot's index.
- BufferSlot mSlots[NUM_BUFFER_SLOTS];
-
- // mDefaultWidth holds the default width of allocated buffers. It is used
- // in requestBuffers() if a width and height of zero is specified.
- uint32_t mDefaultWidth;
-
- // mDefaultHeight holds the default height of allocated buffers. It is used
- // in requestBuffers() if a width and height of zero is specified.
- uint32_t mDefaultHeight;
-
- // mPixelFormat holds the pixel format of allocated buffers. It is used
- // in requestBuffers() if a format of zero is specified.
- uint32_t mPixelFormat;
-
- // mBufferCount is the number of buffer slots that the client and server
- // must maintain. It defaults to MIN_ASYNC_BUFFER_SLOTS and can be changed
- // by calling setBufferCount or setBufferCountServer
- int mBufferCount;
-
- // mClientBufferCount is the number of buffer slots requested by the client.
- // The default is zero, which means the client doesn't care how many buffers
- // there is.
- int mClientBufferCount;
-
- // mServerBufferCount buffer count requested by the server-side
- int mServerBufferCount;
-
- // mCurrentTexture is the buffer slot index of the buffer that is currently
- // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
- // indicating that no buffer slot is currently bound to the texture. Note,
- // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
- // that no buffer is bound to the texture. A call to setBufferCount will
- // reset mCurrentTexture to INVALID_BUFFER_SLOT.
- int mCurrentTexture;
-
// mCurrentTextureBuf is the graphic buffer of the current texture. It's
// possible that this buffer is not associated with any buffer slot, so we
// must track it separately in order to support the getCurrentBuffer method.
@@ -429,72 +197,17 @@ private:
// gets set each time updateTexImage is called.
int64_t mCurrentTimestamp;
- // mNextCrop is the crop rectangle that will be used for the next buffer
- // that gets queued. It is set by calling setCrop.
- Rect mNextCrop;
-
- // mNextTransform is the transform identifier that will be used for the next
- // buffer that gets queued. It is set by calling setTransform.
- uint32_t mNextTransform;
-
- // mNextScalingMode is the scaling mode that will be used for the next
- // buffers that get queued. It is set by calling setScalingMode.
- int mNextScalingMode;
-
// mTexName is the name of the OpenGL texture to which streamed images will
// be bound when updateTexImage is called. It is set at construction time
// changed with a call to setTexName.
const GLuint mTexName;
- // mGraphicBufferAlloc is the connection to SurfaceFlinger that is used to
- // allocate new GraphicBuffer objects.
- sp<IGraphicBufferAlloc> mGraphicBufferAlloc;
-
- // mFrameAvailableListener is the listener object that will be called when a
- // new frame becomes available. If it is not NULL it will be called from
- // queueBuffer.
- sp<FrameAvailableListener> mFrameAvailableListener;
-
- // mSynchronousMode whether we're in synchronous mode or not
- bool mSynchronousMode;
-
- // mAllowSynchronousMode whether we allow synchronous mode or not
- const bool mAllowSynchronousMode;
-
- // mConnectedApi indicates the API that is currently connected to this
- // SurfaceTexture. It defaults to NO_CONNECTED_API (= 0), and gets updated
- // by the connect and disconnect methods.
- int mConnectedApi;
-
- // mDequeueCondition condition used for dequeueBuffer in synchronous mode
- mutable Condition mDequeueCondition;
-
- // mQueue is a FIFO of queued buffers used in synchronous mode
- typedef Vector<int> Fifo;
- Fifo mQueue;
-
- // mAbandoned indicates that the SurfaceTexture will no longer be used to
- // consume images buffers pushed to it using the ISurfaceTexture interface.
- // It is initialized to false, and set to true in the abandon method. A
- // SurfaceTexture that has been abandoned will return the NO_INIT error from
- // all ISurfaceTexture methods capable of returning an error.
- bool mAbandoned;
-
- // mName is a string used to identify the SurfaceTexture in log messages.
- // It is set by the setName method.
- String8 mName;
-
// mUseFenceSync indicates whether creation of the EGL_KHR_fence_sync
// extension should be used to prevent buffers from being dequeued before
// it's safe for them to be written. It gets set at construction time and
// never changes.
const bool mUseFenceSync;
- // mMutex is the mutex used to prevent concurrent access to the member
- // variables of SurfaceTexture objects. It must be locked whenever the
- // member variables are accessed.
- mutable Mutex mMutex;
-
// mTexTarget is the GL texture target with which the GL texture object is
// associated. It is set in the constructor and never changed. It is
// almost always GL_TEXTURE_EXTERNAL_OES except for one use case in Android
@@ -504,11 +217,6 @@ private:
// browser's tile cache exceeds.
const GLenum mTexTarget;
- // mFrameCounter is the free running counter, incremented for every buffer queued
- // with the surface Texture.
- uint64_t mFrameCounter;
-
-
};
// ----------------------------------------------------------------------------
diff --git a/include/private/gui/ComposerService.h b/include/private/gui/ComposerService.h
new file mode 100644
index 0000000..d04491a
--- /dev/null
+++ b/include/private/gui/ComposerService.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_PRIVATE_GUI_COMPOSER_SERVICE_H
+#define ANDROID_PRIVATE_GUI_COMPOSER_SERVICE_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Singleton.h>
+#include <utils/StrongPointer.h>
+
+
+namespace android {
+
+// ---------------------------------------------------------------------------
+
+class IMemoryHeap;
+class ISurfaceComposer;
+class surface_flinger_cblk_t;
+
+// ---------------------------------------------------------------------------
+
+class ComposerService : public Singleton<ComposerService>
+{
+ // these are constants
+ sp<ISurfaceComposer> mComposerService;
+ sp<IMemoryHeap> mServerCblkMemory;
+ surface_flinger_cblk_t volatile* mServerCblk;
+ ComposerService();
+ friend class Singleton<ComposerService>;
+public:
+ static sp<ISurfaceComposer> getComposerService();
+ static surface_flinger_cblk_t const volatile * getControlBlock();
+};
+
+// ---------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_PRIVATE_GUI_COMPOSER_SERVICE_H
diff --git a/include/surfaceflinger/ISurfaceComposer.h b/include/surfaceflinger/ISurfaceComposer.h
index 5eb09c7..58fd89d 100644
--- a/include/surfaceflinger/ISurfaceComposer.h
+++ b/include/surfaceflinger/ISurfaceComposer.h
@@ -33,8 +33,9 @@
namespace android {
// ----------------------------------------------------------------------------
-class IMemoryHeap;
class ComposerState;
+class IDisplayEventConnection;
+class IMemoryHeap;
class ISurfaceComposer : public IInterface
{
@@ -124,13 +125,19 @@ public:
uint32_t reqWidth, uint32_t reqHeight,
uint32_t minLayerZ, uint32_t maxLayerZ) = 0;
+ /* triggers screen off animation */
virtual status_t turnElectronBeamOff(int32_t mode) = 0;
+
+ /* triggers screen on animation */
virtual status_t turnElectronBeamOn(int32_t mode) = 0;
/* verify that an ISurfaceTexture was created by SurfaceFlinger.
*/
virtual bool authenticateSurfaceTexture(
const sp<ISurfaceTexture>& surface) const = 0;
+
+ /* return an IDisplayEventConnection */
+ virtual sp<IDisplayEventConnection> createDisplayEventConnection() = 0;
};
// ----------------------------------------------------------------------------
@@ -151,6 +158,7 @@ public:
TURN_ELECTRON_BEAM_OFF,
TURN_ELECTRON_BEAM_ON,
AUTHENTICATE_SURFACE,
+ CREATE_DISPLAY_EVENT_CONNECTION,
};
virtual status_t onTransact( uint32_t code,
diff --git a/include/surfaceflinger/SurfaceComposerClient.h b/include/surfaceflinger/SurfaceComposerClient.h
index 8226abe..99affda 100644
--- a/include/surfaceflinger/SurfaceComposerClient.h
+++ b/include/surfaceflinger/SurfaceComposerClient.h
@@ -28,7 +28,6 @@
#include <utils/threads.h>
#include <ui/PixelFormat.h>
-#include <ui/Region.h>
#include <surfaceflinger/Surface.h>
@@ -39,30 +38,11 @@ namespace android {
class DisplayInfo;
class Composer;
class IMemoryHeap;
-class ISurfaceComposer;
+class ISurfaceComposerClient;
class Region;
-class surface_flinger_cblk_t;
-struct layer_state_t;
// ---------------------------------------------------------------------------
-class ComposerService : public Singleton<ComposerService>
-{
- // these are constants
- sp<ISurfaceComposer> mComposerService;
- sp<IMemoryHeap> mServerCblkMemory;
- surface_flinger_cblk_t volatile* mServerCblk;
- ComposerService();
- friend class Singleton<ComposerService>;
-public:
- static sp<ISurfaceComposer> getComposerService();
- static surface_flinger_cblk_t const volatile * getControlBlock();
-};
-
-// ---------------------------------------------------------------------------
-
-class Composer;
-
class SurfaceComposerClient : public RefBase
{
friend class Composer;
diff --git a/include/ui/GraphicLog.h b/include/ui/GraphicLog.h
deleted file mode 100644
index ee1b09a..0000000
--- a/include/ui/GraphicLog.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_GRAPHIC_LOG_H
-#define _UI_GRAPHIC_LOG_H
-
-#include <utils/Singleton.h>
-#include <cutils/compiler.h>
-
-namespace android {
-
-class GraphicLog : public Singleton<GraphicLog>
-{
- int32_t mEnabled;
- static void logImpl(int32_t tag, int32_t buffer);
- static void logImpl(int32_t tag, int32_t identity, int32_t buffer);
-
-public:
- enum {
- SF_APP_DEQUEUE_BEFORE = 60100,
- SF_APP_DEQUEUE_AFTER = 60101,
- SF_APP_LOCK_BEFORE = 60102,
- SF_APP_LOCK_AFTER = 60103,
- SF_APP_QUEUE = 60104,
-
- SF_REPAINT = 60105,
- SF_COMPOSITION_COMPLETE = 60106,
- SF_UNLOCK_CLIENTS = 60107,
- SF_SWAP_BUFFERS = 60108,
- SF_REPAINT_DONE = 60109,
-
- SF_FB_POST_BEFORE = 60110,
- SF_FB_POST_AFTER = 60111,
- SF_FB_DEQUEUE_BEFORE = 60112,
- SF_FB_DEQUEUE_AFTER = 60113,
- SF_FB_LOCK_BEFORE = 60114,
- SF_FB_LOCK_AFTER = 60115,
- };
-
- inline void log(int32_t tag, int32_t buffer) {
- if (CC_UNLIKELY(mEnabled))
- logImpl(tag, buffer);
- }
- inline void log(int32_t tag, int32_t identity, int32_t buffer) {
- if (CC_UNLIKELY(mEnabled))
- logImpl(tag, identity, buffer);
- }
-
- GraphicLog();
-
- void setEnabled(bool enable);
-};
-
-}
-
-#endif // _UI_GRAPHIC_LOG_H
-
diff --git a/include/ui/Input.h b/include/ui/Input.h
deleted file mode 100644
index c2cbe1d..0000000
--- a/include/ui/Input.h
+++ /dev/null
@@ -1,897 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_INPUT_H
-#define _UI_INPUT_H
-
-/**
- * Native input event structures.
- */
-
-#include <android/input.h>
-#include <utils/Vector.h>
-#include <utils/KeyedVector.h>
-#include <utils/Timers.h>
-#include <utils/RefBase.h>
-#include <utils/String8.h>
-#include <utils/BitSet.h>
-
-#ifdef HAVE_ANDROID_OS
-class SkMatrix;
-#endif
-
-/*
- * Additional private constants not defined in ndk/ui/input.h.
- */
-enum {
- /* Private control to determine when an app is tracking a key sequence. */
- AKEY_EVENT_FLAG_START_TRACKING = 0x40000000,
-
- /* Key event is inconsistent with previously sent key events. */
- AKEY_EVENT_FLAG_TAINTED = 0x80000000,
-};
-
-enum {
- /* Motion event is inconsistent with previously sent motion events. */
- AMOTION_EVENT_FLAG_TAINTED = 0x80000000,
-};
-
-enum {
- /*
- * Indicates that an input device has switches.
- * This input source flag is hidden from the API because switches are only used by the system
- * and applications have no way to interact with them.
- */
- AINPUT_SOURCE_SWITCH = 0x80000000,
-};
-
-/*
- * SystemUiVisibility constants from View.
- */
-enum {
- ASYSTEM_UI_VISIBILITY_STATUS_BAR_VISIBLE = 0,
- ASYSTEM_UI_VISIBILITY_STATUS_BAR_HIDDEN = 0x00000001,
-};
-
-/*
- * Maximum number of pointers supported per motion event.
- * Smallest number of pointers is 1.
- * (We want at least 10 but some touch controllers obstensibly configured for 10 pointers
- * will occasionally emit 11. There is not much harm making this constant bigger.)
- */
-#define MAX_POINTERS 16
-
-/*
- * Maximum pointer id value supported in a motion event.
- * Smallest pointer id is 0.
- * (This is limited by our use of BitSet32 to track pointer assignments.)
- */
-#define MAX_POINTER_ID 31
-
-/*
- * Declare a concrete type for the NDK's input event forward declaration.
- */
-struct AInputEvent {
- virtual ~AInputEvent() { }
-};
-
-/*
- * Declare a concrete type for the NDK's input device forward declaration.
- */
-struct AInputDevice {
- virtual ~AInputDevice() { }
-};
-
-
-namespace android {
-
-#ifdef HAVE_ANDROID_OS
-class Parcel;
-#endif
-
-/*
- * Flags that flow alongside events in the input dispatch system to help with certain
- * policy decisions such as waking from device sleep.
- *
- * These flags are also defined in frameworks/base/core/java/android/view/WindowManagerPolicy.java.
- */
-enum {
- /* These flags originate in RawEvents and are generally set in the key map.
- * NOTE: If you edit these flags, also edit labels in KeycodeLabels.h. */
-
- POLICY_FLAG_WAKE = 0x00000001,
- POLICY_FLAG_WAKE_DROPPED = 0x00000002,
- POLICY_FLAG_SHIFT = 0x00000004,
- POLICY_FLAG_CAPS_LOCK = 0x00000008,
- POLICY_FLAG_ALT = 0x00000010,
- POLICY_FLAG_ALT_GR = 0x00000020,
- POLICY_FLAG_MENU = 0x00000040,
- POLICY_FLAG_LAUNCHER = 0x00000080,
- POLICY_FLAG_VIRTUAL = 0x00000100,
- POLICY_FLAG_FUNCTION = 0x00000200,
-
- POLICY_FLAG_RAW_MASK = 0x0000ffff,
-
- /* These flags are set by the input dispatcher. */
-
- // Indicates that the input event was injected.
- POLICY_FLAG_INJECTED = 0x01000000,
-
- // Indicates that the input event is from a trusted source such as a directly attached
- // input device or an application with system-wide event injection permission.
- POLICY_FLAG_TRUSTED = 0x02000000,
-
- // Indicates that the input event has passed through an input filter.
- POLICY_FLAG_FILTERED = 0x04000000,
-
- // Disables automatic key repeating behavior.
- POLICY_FLAG_DISABLE_KEY_REPEAT = 0x08000000,
-
- /* These flags are set by the input reader policy as it intercepts each event. */
-
- // Indicates that the screen was off when the event was received and the event
- // should wake the device.
- POLICY_FLAG_WOKE_HERE = 0x10000000,
-
- // Indicates that the screen was dim when the event was received and the event
- // should brighten the device.
- POLICY_FLAG_BRIGHT_HERE = 0x20000000,
-
- // Indicates that the event should be dispatched to applications.
- // The input event should still be sent to the InputDispatcher so that it can see all
- // input events received include those that it will not deliver.
- POLICY_FLAG_PASS_TO_USER = 0x40000000,
-};
-
-/*
- * Describes the basic configuration of input devices that are present.
- */
-struct InputConfiguration {
- enum {
- TOUCHSCREEN_UNDEFINED = 0,
- TOUCHSCREEN_NOTOUCH = 1,
- TOUCHSCREEN_STYLUS = 2,
- TOUCHSCREEN_FINGER = 3
- };
-
- enum {
- KEYBOARD_UNDEFINED = 0,
- KEYBOARD_NOKEYS = 1,
- KEYBOARD_QWERTY = 2,
- KEYBOARD_12KEY = 3
- };
-
- enum {
- NAVIGATION_UNDEFINED = 0,
- NAVIGATION_NONAV = 1,
- NAVIGATION_DPAD = 2,
- NAVIGATION_TRACKBALL = 3,
- NAVIGATION_WHEEL = 4
- };
-
- int32_t touchScreen;
- int32_t keyboard;
- int32_t navigation;
-};
-
-/*
- * Pointer coordinate data.
- */
-struct PointerCoords {
- enum { MAX_AXES = 14 }; // 14 so that sizeof(PointerCoords) == 64
-
- // Bitfield of axes that are present in this structure.
- uint64_t bits;
-
- // Values of axes that are stored in this structure packed in order by axis id
- // for each axis that is present in the structure according to 'bits'.
- float values[MAX_AXES];
-
- inline void clear() {
- bits = 0;
- }
-
- float getAxisValue(int32_t axis) const;
- status_t setAxisValue(int32_t axis, float value);
-
- void scale(float scale);
-
- inline float getX() const {
- return getAxisValue(AMOTION_EVENT_AXIS_X);
- }
-
- inline float getY() const {
- return getAxisValue(AMOTION_EVENT_AXIS_Y);
- }
-
-#ifdef HAVE_ANDROID_OS
- status_t readFromParcel(Parcel* parcel);
- status_t writeToParcel(Parcel* parcel) const;
-#endif
-
- bool operator==(const PointerCoords& other) const;
- inline bool operator!=(const PointerCoords& other) const {
- return !(*this == other);
- }
-
- void copyFrom(const PointerCoords& other);
-
-private:
- void tooManyAxes(int axis);
-};
-
-/*
- * Pointer property data.
- */
-struct PointerProperties {
- // The id of the pointer.
- int32_t id;
-
- // The pointer tool type.
- int32_t toolType;
-
- inline void clear() {
- id = -1;
- toolType = 0;
- }
-
- bool operator==(const PointerProperties& other) const;
- inline bool operator!=(const PointerProperties& other) const {
- return !(*this == other);
- }
-
- void copyFrom(const PointerProperties& other);
-};
-
-/*
- * Input events.
- */
-class InputEvent : public AInputEvent {
-public:
- virtual ~InputEvent() { }
-
- virtual int32_t getType() const = 0;
-
- inline int32_t getDeviceId() const { return mDeviceId; }
-
- inline int32_t getSource() const { return mSource; }
-
- inline void setSource(int32_t source) { mSource = source; }
-
-protected:
- void initialize(int32_t deviceId, int32_t source);
- void initialize(const InputEvent& from);
-
- int32_t mDeviceId;
- int32_t mSource;
-};
-
-/*
- * Key events.
- */
-class KeyEvent : public InputEvent {
-public:
- virtual ~KeyEvent() { }
-
- virtual int32_t getType() const { return AINPUT_EVENT_TYPE_KEY; }
-
- inline int32_t getAction() const { return mAction; }
-
- inline int32_t getFlags() const { return mFlags; }
-
- inline int32_t getKeyCode() const { return mKeyCode; }
-
- inline int32_t getScanCode() const { return mScanCode; }
-
- inline int32_t getMetaState() const { return mMetaState; }
-
- inline int32_t getRepeatCount() const { return mRepeatCount; }
-
- inline nsecs_t getDownTime() const { return mDownTime; }
-
- inline nsecs_t getEventTime() const { return mEventTime; }
-
- // Return true if this event may have a default action implementation.
- static bool hasDefaultAction(int32_t keyCode);
- bool hasDefaultAction() const;
-
- // Return true if this event represents a system key.
- static bool isSystemKey(int32_t keyCode);
- bool isSystemKey() const;
-
- void initialize(
- int32_t deviceId,
- int32_t source,
- int32_t action,
- int32_t flags,
- int32_t keyCode,
- int32_t scanCode,
- int32_t metaState,
- int32_t repeatCount,
- nsecs_t downTime,
- nsecs_t eventTime);
- void initialize(const KeyEvent& from);
-
-protected:
- int32_t mAction;
- int32_t mFlags;
- int32_t mKeyCode;
- int32_t mScanCode;
- int32_t mMetaState;
- int32_t mRepeatCount;
- nsecs_t mDownTime;
- nsecs_t mEventTime;
-};
-
-/*
- * Motion events.
- */
-class MotionEvent : public InputEvent {
-public:
- virtual ~MotionEvent() { }
-
- virtual int32_t getType() const { return AINPUT_EVENT_TYPE_MOTION; }
-
- inline int32_t getAction() const { return mAction; }
-
- inline int32_t getActionMasked() const { return mAction & AMOTION_EVENT_ACTION_MASK; }
-
- inline int32_t getActionIndex() const {
- return (mAction & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
- >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
- }
-
- inline void setAction(int32_t action) { mAction = action; }
-
- inline int32_t getFlags() const { return mFlags; }
-
- inline void setFlags(int32_t flags) { mFlags = flags; }
-
- inline int32_t getEdgeFlags() const { return mEdgeFlags; }
-
- inline void setEdgeFlags(int32_t edgeFlags) { mEdgeFlags = edgeFlags; }
-
- inline int32_t getMetaState() const { return mMetaState; }
-
- inline void setMetaState(int32_t metaState) { mMetaState = metaState; }
-
- inline int32_t getButtonState() const { return mButtonState; }
-
- inline float getXOffset() const { return mXOffset; }
-
- inline float getYOffset() const { return mYOffset; }
-
- inline float getXPrecision() const { return mXPrecision; }
-
- inline float getYPrecision() const { return mYPrecision; }
-
- inline nsecs_t getDownTime() const { return mDownTime; }
-
- inline void setDownTime(nsecs_t downTime) { mDownTime = downTime; }
-
- inline size_t getPointerCount() const { return mPointerProperties.size(); }
-
- inline const PointerProperties* getPointerProperties(size_t pointerIndex) const {
- return &mPointerProperties[pointerIndex];
- }
-
- inline int32_t getPointerId(size_t pointerIndex) const {
- return mPointerProperties[pointerIndex].id;
- }
-
- inline int32_t getToolType(size_t pointerIndex) const {
- return mPointerProperties[pointerIndex].toolType;
- }
-
- inline nsecs_t getEventTime() const { return mSampleEventTimes[getHistorySize()]; }
-
- const PointerCoords* getRawPointerCoords(size_t pointerIndex) const;
-
- float getRawAxisValue(int32_t axis, size_t pointerIndex) const;
-
- inline float getRawX(size_t pointerIndex) const {
- return getRawAxisValue(AMOTION_EVENT_AXIS_X, pointerIndex);
- }
-
- inline float getRawY(size_t pointerIndex) const {
- return getRawAxisValue(AMOTION_EVENT_AXIS_Y, pointerIndex);
- }
-
- float getAxisValue(int32_t axis, size_t pointerIndex) const;
-
- inline float getX(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_X, pointerIndex);
- }
-
- inline float getY(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_Y, pointerIndex);
- }
-
- inline float getPressure(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pointerIndex);
- }
-
- inline float getSize(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_SIZE, pointerIndex);
- }
-
- inline float getTouchMajor(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerIndex);
- }
-
- inline float getTouchMinor(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerIndex);
- }
-
- inline float getToolMajor(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerIndex);
- }
-
- inline float getToolMinor(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, pointerIndex);
- }
-
- inline float getOrientation(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, pointerIndex);
- }
-
- inline size_t getHistorySize() const { return mSampleEventTimes.size() - 1; }
-
- inline nsecs_t getHistoricalEventTime(size_t historicalIndex) const {
- return mSampleEventTimes[historicalIndex];
- }
-
- const PointerCoords* getHistoricalRawPointerCoords(
- size_t pointerIndex, size_t historicalIndex) const;
-
- float getHistoricalRawAxisValue(int32_t axis, size_t pointerIndex,
- size_t historicalIndex) const;
-
- inline float getHistoricalRawX(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalRawAxisValue(
- AMOTION_EVENT_AXIS_X, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalRawY(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalRawAxisValue(
- AMOTION_EVENT_AXIS_Y, pointerIndex, historicalIndex);
- }
-
- float getHistoricalAxisValue(int32_t axis, size_t pointerIndex, size_t historicalIndex) const;
-
- inline float getHistoricalX(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_X, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalY(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_Y, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalPressure(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_PRESSURE, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalSize(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_SIZE, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalTouchMajor(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalTouchMinor(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalToolMajor(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalToolMinor(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_TOOL_MINOR, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalOrientation(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_ORIENTATION, pointerIndex, historicalIndex);
- }
-
- ssize_t findPointerIndex(int32_t pointerId) const;
-
- void initialize(
- int32_t deviceId,
- int32_t source,
- int32_t action,
- int32_t flags,
- int32_t edgeFlags,
- int32_t metaState,
- int32_t buttonState,
- float xOffset,
- float yOffset,
- float xPrecision,
- float yPrecision,
- nsecs_t downTime,
- nsecs_t eventTime,
- size_t pointerCount,
- const PointerProperties* pointerProperties,
- const PointerCoords* pointerCoords);
-
- void copyFrom(const MotionEvent* other, bool keepHistory);
-
- void addSample(
- nsecs_t eventTime,
- const PointerCoords* pointerCoords);
-
- void offsetLocation(float xOffset, float yOffset);
-
- void scale(float scaleFactor);
-
-#ifdef HAVE_ANDROID_OS
- void transform(const SkMatrix* matrix);
-
- status_t readFromParcel(Parcel* parcel);
- status_t writeToParcel(Parcel* parcel) const;
-#endif
-
- static bool isTouchEvent(int32_t source, int32_t action);
- inline bool isTouchEvent() const {
- return isTouchEvent(mSource, mAction);
- }
-
- // Low-level accessors.
- inline const PointerProperties* getPointerProperties() const {
- return mPointerProperties.array();
- }
- inline const nsecs_t* getSampleEventTimes() const { return mSampleEventTimes.array(); }
- inline const PointerCoords* getSamplePointerCoords() const {
- return mSamplePointerCoords.array();
- }
-
-protected:
- int32_t mAction;
- int32_t mFlags;
- int32_t mEdgeFlags;
- int32_t mMetaState;
- int32_t mButtonState;
- float mXOffset;
- float mYOffset;
- float mXPrecision;
- float mYPrecision;
- nsecs_t mDownTime;
- Vector<PointerProperties> mPointerProperties;
- Vector<nsecs_t> mSampleEventTimes;
- Vector<PointerCoords> mSamplePointerCoords;
-};
-
-/*
- * Input event factory.
- */
-class InputEventFactoryInterface {
-protected:
- virtual ~InputEventFactoryInterface() { }
-
-public:
- InputEventFactoryInterface() { }
-
- virtual KeyEvent* createKeyEvent() = 0;
- virtual MotionEvent* createMotionEvent() = 0;
-};
-
-/*
- * A simple input event factory implementation that uses a single preallocated instance
- * of each type of input event that are reused for each request.
- */
-class PreallocatedInputEventFactory : public InputEventFactoryInterface {
-public:
- PreallocatedInputEventFactory() { }
- virtual ~PreallocatedInputEventFactory() { }
-
- virtual KeyEvent* createKeyEvent() { return & mKeyEvent; }
- virtual MotionEvent* createMotionEvent() { return & mMotionEvent; }
-
-private:
- KeyEvent mKeyEvent;
- MotionEvent mMotionEvent;
-};
-
-/*
- * Calculates the velocity of pointer movements over time.
- */
-class VelocityTracker {
-public:
- // Default polynomial degree. (used by getVelocity)
- static const uint32_t DEFAULT_DEGREE = 2;
-
- // Default sample horizon. (used by getVelocity)
- // We don't use too much history by default since we want to react to quick
- // changes in direction.
- static const nsecs_t DEFAULT_HORIZON = 100 * 1000000; // 100 ms
-
- struct Position {
- float x, y;
- };
-
- struct Estimator {
- static const size_t MAX_DEGREE = 2;
-
- // Polynomial coefficients describing motion in X and Y.
- float xCoeff[MAX_DEGREE + 1], yCoeff[MAX_DEGREE + 1];
-
- // Polynomial degree (number of coefficients), or zero if no information is
- // available.
- uint32_t degree;
-
- // Confidence (coefficient of determination), between 0 (no fit) and 1 (perfect fit).
- float confidence;
-
- inline void clear() {
- degree = 0;
- confidence = 0;
- for (size_t i = 0; i <= MAX_DEGREE; i++) {
- xCoeff[i] = 0;
- yCoeff[i] = 0;
- }
- }
- };
-
- VelocityTracker();
-
- // Resets the velocity tracker state.
- void clear();
-
- // Resets the velocity tracker state for specific pointers.
- // Call this method when some pointers have changed and may be reusing
- // an id that was assigned to a different pointer earlier.
- void clearPointers(BitSet32 idBits);
-
- // Adds movement information for a set of pointers.
- // The idBits bitfield specifies the pointer ids of the pointers whose positions
- // are included in the movement.
- // The positions array contains position information for each pointer in order by
- // increasing id. Its size should be equal to the number of one bits in idBits.
- void addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions);
-
- // Adds movement information for all pointers in a MotionEvent, including historical samples.
- void addMovement(const MotionEvent* event);
-
- // Gets the velocity of the specified pointer id in position units per second.
- // Returns false and sets the velocity components to zero if there is
- // insufficient movement information for the pointer.
- bool getVelocity(uint32_t id, float* outVx, float* outVy) const;
-
- // Gets a quadratic estimator for the movements of the specified pointer id.
- // Returns false and clears the estimator if there is no information available
- // about the pointer.
- bool getEstimator(uint32_t id, uint32_t degree, nsecs_t horizon,
- Estimator* outEstimator) const;
-
- // Gets the active pointer id, or -1 if none.
- inline int32_t getActivePointerId() const { return mActivePointerId; }
-
- // Gets a bitset containing all pointer ids from the most recent movement.
- inline BitSet32 getCurrentPointerIdBits() const { return mMovements[mIndex].idBits; }
-
-private:
- // Number of samples to keep.
- static const uint32_t HISTORY_SIZE = 20;
-
- struct Movement {
- nsecs_t eventTime;
- BitSet32 idBits;
- Position positions[MAX_POINTERS];
-
- inline const Position& getPosition(uint32_t id) const {
- return positions[idBits.getIndexOfBit(id)];
- }
- };
-
- uint32_t mIndex;
- Movement mMovements[HISTORY_SIZE];
- int32_t mActivePointerId;
-};
-
-
-/*
- * Specifies parameters that govern pointer or wheel acceleration.
- */
-struct VelocityControlParameters {
- // A scale factor that is multiplied with the raw velocity deltas
- // prior to applying any other velocity control factors. The scale
- // factor should be used to adapt the input device resolution
- // (eg. counts per inch) to the output device resolution (eg. pixels per inch).
- //
- // Must be a positive value.
- // Default is 1.0 (no scaling).
- float scale;
-
- // The scaled speed at which acceleration begins to be applied.
- // This value establishes the upper bound of a low speed regime for
- // small precise motions that are performed without any acceleration.
- //
- // Must be a non-negative value.
- // Default is 0.0 (no low threshold).
- float lowThreshold;
-
- // The scaled speed at which maximum acceleration is applied.
- // The difference between highThreshold and lowThreshold controls
- // the range of speeds over which the acceleration factor is interpolated.
- // The wider the range, the smoother the acceleration.
- //
- // Must be a non-negative value greater than or equal to lowThreshold.
- // Default is 0.0 (no high threshold).
- float highThreshold;
-
- // The acceleration factor.
- // When the speed is above the low speed threshold, the velocity will scaled
- // by an interpolated value between 1.0 and this amount.
- //
- // Must be a positive greater than or equal to 1.0.
- // Default is 1.0 (no acceleration).
- float acceleration;
-
- VelocityControlParameters() :
- scale(1.0f), lowThreshold(0.0f), highThreshold(0.0f), acceleration(1.0f) {
- }
-
- VelocityControlParameters(float scale, float lowThreshold,
- float highThreshold, float acceleration) :
- scale(scale), lowThreshold(lowThreshold),
- highThreshold(highThreshold), acceleration(acceleration) {
- }
-};
-
-/*
- * Implements mouse pointer and wheel speed control and acceleration.
- */
-class VelocityControl {
-public:
- VelocityControl();
-
- /* Sets the various parameters. */
- void setParameters(const VelocityControlParameters& parameters);
-
- /* Resets the current movement counters to zero.
- * This has the effect of nullifying any acceleration. */
- void reset();
-
- /* Translates a raw movement delta into an appropriately
- * scaled / accelerated delta based on the current velocity. */
- void move(nsecs_t eventTime, float* deltaX, float* deltaY);
-
-private:
- // If no movements are received within this amount of time,
- // we assume the movement has stopped and reset the movement counters.
- static const nsecs_t STOP_TIME = 500 * 1000000; // 500 ms
-
- VelocityControlParameters mParameters;
-
- nsecs_t mLastMovementTime;
- VelocityTracker::Position mRawPosition;
- VelocityTracker mVelocityTracker;
-};
-
-
-/*
- * Describes the characteristics and capabilities of an input device.
- */
-class InputDeviceInfo {
-public:
- InputDeviceInfo();
- InputDeviceInfo(const InputDeviceInfo& other);
- ~InputDeviceInfo();
-
- struct MotionRange {
- int32_t axis;
- uint32_t source;
- float min;
- float max;
- float flat;
- float fuzz;
- };
-
- void initialize(int32_t id, const String8& name);
-
- inline int32_t getId() const { return mId; }
- inline const String8 getName() const { return mName; }
- inline uint32_t getSources() const { return mSources; }
-
- const MotionRange* getMotionRange(int32_t axis, uint32_t source) const;
-
- void addSource(uint32_t source);
- void addMotionRange(int32_t axis, uint32_t source,
- float min, float max, float flat, float fuzz);
- void addMotionRange(const MotionRange& range);
-
- inline void setKeyboardType(int32_t keyboardType) { mKeyboardType = keyboardType; }
- inline int32_t getKeyboardType() const { return mKeyboardType; }
-
- inline void setKeyCharacterMapFile(const String8& value) { mKeyCharacterMapFile = value; }
- inline const String8& getKeyCharacterMapFile() const { return mKeyCharacterMapFile; }
-
- inline const Vector<MotionRange>& getMotionRanges() const {
- return mMotionRanges;
- }
-
-private:
- int32_t mId;
- String8 mName;
- uint32_t mSources;
- int32_t mKeyboardType;
- String8 mKeyCharacterMapFile;
-
- Vector<MotionRange> mMotionRanges;
-};
-
-/*
- * Identifies a device.
- */
-struct InputDeviceIdentifier {
- inline InputDeviceIdentifier() :
- bus(0), vendor(0), product(0), version(0) {
- }
-
- String8 name;
- String8 location;
- String8 uniqueId;
- uint16_t bus;
- uint16_t vendor;
- uint16_t product;
- uint16_t version;
-};
-
-/* Types of input device configuration files. */
-enum InputDeviceConfigurationFileType {
- INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION = 0, /* .idc file */
- INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_LAYOUT = 1, /* .kl file */
- INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_CHARACTER_MAP = 2, /* .kcm file */
-};
-
-/*
- * Gets the path of an input device configuration file, if one is available.
- * Considers both system provided and user installed configuration files.
- *
- * The device identifier is used to construct several default configuration file
- * names to try based on the device name, vendor, product, and version.
- *
- * Returns an empty string if not found.
- */
-extern String8 getInputDeviceConfigurationFilePathByDeviceIdentifier(
- const InputDeviceIdentifier& deviceIdentifier,
- InputDeviceConfigurationFileType type);
-
-/*
- * Gets the path of an input device configuration file, if one is available.
- * Considers both system provided and user installed configuration files.
- *
- * The name is case-sensitive and is used to construct the filename to resolve.
- * All characters except 'a'-'z', 'A'-'Z', '0'-'9', '-', and '_' are replaced by underscores.
- *
- * Returns an empty string if not found.
- */
-extern String8 getInputDeviceConfigurationFilePathByName(
- const String8& name, InputDeviceConfigurationFileType type);
-
-} // namespace android
-
-#endif // _UI_INPUT_H
diff --git a/include/ui/InputTransport.h b/include/ui/InputTransport.h
deleted file mode 100644
index 95e4447..0000000
--- a/include/ui/InputTransport.h
+++ /dev/null
@@ -1,338 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_INPUT_TRANSPORT_H
-#define _UI_INPUT_TRANSPORT_H
-
-/**
- * Native input transport.
- *
- * Uses anonymous shared memory as a whiteboard for sending input events from an
- * InputPublisher to an InputConsumer and ensuring appropriate synchronization.
- * One interesting feature is that published events can be updated in place as long as they
- * have not yet been consumed.
- *
- * The InputPublisher and InputConsumer only take care of transferring event data
- * over an InputChannel and sending synchronization signals. The InputDispatcher and InputQueue
- * build on these abstractions to add multiplexing and queueing.
- */
-
-#include <semaphore.h>
-#include <ui/Input.h>
-#include <utils/Errors.h>
-#include <utils/Timers.h>
-#include <utils/RefBase.h>
-#include <utils/String8.h>
-
-namespace android {
-
-/*
- * An input channel consists of a shared memory buffer and a pair of pipes
- * used to send input messages from an InputPublisher to an InputConsumer
- * across processes. Each channel has a descriptive name for debugging purposes.
- *
- * Each endpoint has its own InputChannel object that specifies its own file descriptors.
- *
- * The input channel is closed when all references to it are released.
- */
-class InputChannel : public RefBase {
-protected:
- virtual ~InputChannel();
-
-public:
- InputChannel(const String8& name, int32_t ashmemFd, int32_t receivePipeFd,
- int32_t sendPipeFd);
-
- /* Creates a pair of input channels and their underlying shared memory buffers
- * and pipes.
- *
- * Returns OK on success.
- */
- static status_t openInputChannelPair(const String8& name,
- sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
-
- inline String8 getName() const { return mName; }
- inline int32_t getAshmemFd() const { return mAshmemFd; }
- inline int32_t getReceivePipeFd() const { return mReceivePipeFd; }
- inline int32_t getSendPipeFd() const { return mSendPipeFd; }
-
- /* Sends a signal to the other endpoint.
- *
- * Returns OK on success.
- * Returns DEAD_OBJECT if the channel's peer has been closed.
- * Other errors probably indicate that the channel is broken.
- */
- status_t sendSignal(char signal);
-
- /* Receives a signal send by the other endpoint.
- * (Should only call this after poll() indicates that the receivePipeFd has available input.)
- *
- * Returns OK on success.
- * Returns WOULD_BLOCK if there is no signal present.
- * Returns DEAD_OBJECT if the channel's peer has been closed.
- * Other errors probably indicate that the channel is broken.
- */
- status_t receiveSignal(char* outSignal);
-
-private:
- String8 mName;
- int32_t mAshmemFd;
- int32_t mReceivePipeFd;
- int32_t mSendPipeFd;
-};
-
-/*
- * Private intermediate representation of input events as messages written into an
- * ashmem buffer.
- */
-struct InputMessage {
- /* Semaphore count is set to 1 when the message is published.
- * It becomes 0 transiently while the publisher updates the message.
- * It becomes 0 permanently when the consumer consumes the message.
- */
- sem_t semaphore;
-
- /* Initialized to false by the publisher.
- * Set to true by the consumer when it consumes the message.
- */
- bool consumed;
-
- int32_t type;
-
- struct SampleData {
- nsecs_t eventTime;
- PointerCoords coords[0]; // variable length
- };
-
- int32_t deviceId;
- int32_t source;
-
- union {
- struct {
- int32_t action;
- int32_t flags;
- int32_t keyCode;
- int32_t scanCode;
- int32_t metaState;
- int32_t repeatCount;
- nsecs_t downTime;
- nsecs_t eventTime;
- } key;
-
- struct {
- int32_t action;
- int32_t flags;
- int32_t metaState;
- int32_t buttonState;
- int32_t edgeFlags;
- nsecs_t downTime;
- float xOffset;
- float yOffset;
- float xPrecision;
- float yPrecision;
- size_t pointerCount;
- PointerProperties pointerProperties[MAX_POINTERS];
- size_t sampleCount;
- SampleData sampleData[0]; // variable length
- } motion;
- };
-
- /* Gets the number of bytes to add to step to the next SampleData object in a motion
- * event message for a given number of pointers.
- */
- static inline size_t sampleDataStride(size_t pointerCount) {
- return sizeof(InputMessage::SampleData) + pointerCount * sizeof(PointerCoords);
- }
-
- /* Adds the SampleData stride to the given pointer. */
- static inline SampleData* sampleDataPtrIncrement(SampleData* ptr, size_t stride) {
- return reinterpret_cast<InputMessage::SampleData*>(reinterpret_cast<char*>(ptr) + stride);
- }
-};
-
-/*
- * Publishes input events to an anonymous shared memory buffer.
- * Uses atomic operations to coordinate shared access with a single concurrent consumer.
- */
-class InputPublisher {
-public:
- /* Creates a publisher associated with an input channel. */
- explicit InputPublisher(const sp<InputChannel>& channel);
-
- /* Destroys the publisher and releases its input channel. */
- ~InputPublisher();
-
- /* Gets the underlying input channel. */
- inline sp<InputChannel> getChannel() { return mChannel; }
-
- /* Prepares the publisher for use. Must be called before it is used.
- * Returns OK on success.
- *
- * This method implicitly calls reset(). */
- status_t initialize();
-
- /* Resets the publisher to its initial state and unpins its ashmem buffer.
- * Returns OK on success.
- *
- * Should be called after an event has been consumed to release resources used by the
- * publisher until the next event is ready to be published.
- */
- status_t reset();
-
- /* Publishes a key event to the ashmem buffer.
- *
- * Returns OK on success.
- * Returns INVALID_OPERATION if the publisher has not been reset.
- */
- status_t publishKeyEvent(
- int32_t deviceId,
- int32_t source,
- int32_t action,
- int32_t flags,
- int32_t keyCode,
- int32_t scanCode,
- int32_t metaState,
- int32_t repeatCount,
- nsecs_t downTime,
- nsecs_t eventTime);
-
- /* Publishes a motion event to the ashmem buffer.
- *
- * Returns OK on success.
- * Returns INVALID_OPERATION if the publisher has not been reset.
- * Returns BAD_VALUE if pointerCount is less than 1 or greater than MAX_POINTERS.
- */
- status_t publishMotionEvent(
- int32_t deviceId,
- int32_t source,
- int32_t action,
- int32_t flags,
- int32_t edgeFlags,
- int32_t metaState,
- int32_t buttonState,
- float xOffset,
- float yOffset,
- float xPrecision,
- float yPrecision,
- nsecs_t downTime,
- nsecs_t eventTime,
- size_t pointerCount,
- const PointerProperties* pointerProperties,
- const PointerCoords* pointerCoords);
-
- /* Appends a motion sample to a motion event unless already consumed.
- *
- * Returns OK on success.
- * Returns INVALID_OPERATION if the current event is not a AMOTION_EVENT_ACTION_MOVE event.
- * Returns FAILED_TRANSACTION if the current event has already been consumed.
- * Returns NO_MEMORY if the buffer is full and no additional samples can be added.
- */
- status_t appendMotionSample(
- nsecs_t eventTime,
- const PointerCoords* pointerCoords);
-
- /* Sends a dispatch signal to the consumer to inform it that a new message is available.
- *
- * Returns OK on success.
- * Errors probably indicate that the channel is broken.
- */
- status_t sendDispatchSignal();
-
- /* Receives the finished signal from the consumer in reply to the original dispatch signal.
- * Returns whether the consumer handled the message.
- *
- * Returns OK on success.
- * Returns WOULD_BLOCK if there is no signal present.
- * Other errors probably indicate that the channel is broken.
- */
- status_t receiveFinishedSignal(bool* outHandled);
-
-private:
- sp<InputChannel> mChannel;
-
- size_t mAshmemSize;
- InputMessage* mSharedMessage;
- bool mPinned;
- bool mSemaphoreInitialized;
- bool mWasDispatched;
-
- size_t mMotionEventPointerCount;
- InputMessage::SampleData* mMotionEventSampleDataTail;
- size_t mMotionEventSampleDataStride;
-
- status_t publishInputEvent(
- int32_t type,
- int32_t deviceId,
- int32_t source);
-};
-
-/*
- * Consumes input events from an anonymous shared memory buffer.
- * Uses atomic operations to coordinate shared access with a single concurrent publisher.
- */
-class InputConsumer {
-public:
- /* Creates a consumer associated with an input channel. */
- explicit InputConsumer(const sp<InputChannel>& channel);
-
- /* Destroys the consumer and releases its input channel. */
- ~InputConsumer();
-
- /* Gets the underlying input channel. */
- inline sp<InputChannel> getChannel() { return mChannel; }
-
- /* Prepares the consumer for use. Must be called before it is used. */
- status_t initialize();
-
- /* Consumes the input event in the buffer and copies its contents into
- * an InputEvent object created using the specified factory.
- * This operation will block if the publisher is updating the event.
- *
- * Returns OK on success.
- * Returns INVALID_OPERATION if there is no currently published event.
- * Returns NO_MEMORY if the event could not be created.
- */
- status_t consume(InputEventFactoryInterface* factory, InputEvent** outEvent);
-
- /* Sends a finished signal to the publisher to inform it that the current message is
- * finished processing and specifies whether the message was handled by the consumer.
- *
- * Returns OK on success.
- * Errors probably indicate that the channel is broken.
- */
- status_t sendFinishedSignal(bool handled);
-
- /* Receives the dispatched signal from the publisher.
- *
- * Returns OK on success.
- * Returns WOULD_BLOCK if there is no signal present.
- * Other errors probably indicate that the channel is broken.
- */
- status_t receiveDispatchSignal();
-
-private:
- sp<InputChannel> mChannel;
-
- size_t mAshmemSize;
- InputMessage* mSharedMessage;
-
- void populateKeyEvent(KeyEvent* keyEvent) const;
- void populateMotionEvent(MotionEvent* motionEvent) const;
-};
-
-} // namespace android
-
-#endif // _UI_INPUT_TRANSPORT_H
diff --git a/include/ui/KeyCharacterMap.h b/include/ui/KeyCharacterMap.h
deleted file mode 100644
index be14432..0000000
--- a/include/ui/KeyCharacterMap.h
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_KEY_CHARACTER_MAP_H
-#define _UI_KEY_CHARACTER_MAP_H
-
-#include <stdint.h>
-
-#include <ui/Input.h>
-#include <utils/Errors.h>
-#include <utils/KeyedVector.h>
-#include <utils/Tokenizer.h>
-#include <utils/String8.h>
-#include <utils/Unicode.h>
-
-namespace android {
-
-/**
- * Describes a mapping from Android key codes to characters.
- * Also specifies other functions of the keyboard such as the keyboard type
- * and key modifier semantics.
- */
-class KeyCharacterMap {
-public:
- enum KeyboardType {
- KEYBOARD_TYPE_UNKNOWN = 0,
- KEYBOARD_TYPE_NUMERIC = 1,
- KEYBOARD_TYPE_PREDICTIVE = 2,
- KEYBOARD_TYPE_ALPHA = 3,
- KEYBOARD_TYPE_FULL = 4,
- KEYBOARD_TYPE_SPECIAL_FUNCTION = 5,
- };
-
- // Substitute key code and meta state for fallback action.
- struct FallbackAction {
- int32_t keyCode;
- int32_t metaState;
- };
-
- ~KeyCharacterMap();
-
- static status_t load(const String8& filename, KeyCharacterMap** outMap);
-
- /* Gets the keyboard type. */
- int32_t getKeyboardType() const;
-
- /* Gets the primary character for this key as in the label physically printed on it.
- * Returns 0 if none (eg. for non-printing keys). */
- char16_t getDisplayLabel(int32_t keyCode) const;
-
- /* Gets the Unicode character for the number or symbol generated by the key
- * when the keyboard is used as a dialing pad.
- * Returns 0 if no number or symbol is generated.
- */
- char16_t getNumber(int32_t keyCode) const;
-
- /* Gets the Unicode character generated by the key and meta key modifiers.
- * Returns 0 if no character is generated.
- */
- char16_t getCharacter(int32_t keyCode, int32_t metaState) const;
-
- /* Gets the fallback action to use by default if the application does not
- * handle the specified key.
- * Returns true if an action was available, false if none.
- */
- bool getFallbackAction(int32_t keyCode, int32_t metaState,
- FallbackAction* outFallbackAction) const;
-
- /* Gets the first matching Unicode character that can be generated by the key,
- * preferring the one with the specified meta key modifiers.
- * Returns 0 if no matching character is generated.
- */
- char16_t getMatch(int32_t keyCode, const char16_t* chars,
- size_t numChars, int32_t metaState) const;
-
- /* Gets a sequence of key events that could plausibly generate the specified
- * character sequence. Returns false if some of the characters cannot be generated.
- */
- bool getEvents(int32_t deviceId, const char16_t* chars, size_t numChars,
- Vector<KeyEvent>& outEvents) const;
-
-private:
- struct Behavior {
- Behavior();
-
- /* The next behavior in the list, or NULL if none. */
- Behavior* next;
-
- /* The meta key modifiers for this behavior. */
- int32_t metaState;
-
- /* The character to insert. */
- char16_t character;
-
- /* The fallback keycode if the key is not handled. */
- int32_t fallbackKeyCode;
- };
-
- struct Key {
- Key();
- ~Key();
-
- /* The single character label printed on the key, or 0 if none. */
- char16_t label;
-
- /* The number or symbol character generated by the key, or 0 if none. */
- char16_t number;
-
- /* The list of key behaviors sorted from most specific to least specific
- * meta key binding. */
- Behavior* firstBehavior;
- };
-
- class Parser {
- enum State {
- STATE_TOP = 0,
- STATE_KEY = 1,
- };
-
- enum {
- PROPERTY_LABEL = 1,
- PROPERTY_NUMBER = 2,
- PROPERTY_META = 3,
- };
-
- struct Property {
- inline Property(int32_t property = 0, int32_t metaState = 0) :
- property(property), metaState(metaState) { }
-
- int32_t property;
- int32_t metaState;
- };
-
- KeyCharacterMap* mMap;
- Tokenizer* mTokenizer;
- State mState;
- int32_t mKeyCode;
-
- public:
- Parser(KeyCharacterMap* map, Tokenizer* tokenizer);
- ~Parser();
- status_t parse();
-
- private:
- status_t parseType();
- status_t parseKey();
- status_t parseKeyProperty();
- status_t parseModifier(const String8& token, int32_t* outMetaState);
- status_t parseCharacterLiteral(char16_t* outCharacter);
- };
-
- KeyedVector<int32_t, Key*> mKeys;
- int mType;
-
- KeyCharacterMap();
-
- bool getKey(int32_t keyCode, const Key** outKey) const;
- bool getKeyBehavior(int32_t keyCode, int32_t metaState,
- const Key** outKey, const Behavior** outBehavior) const;
-
- bool findKey(char16_t ch, int32_t* outKeyCode, int32_t* outMetaState) const;
-
- static void addKey(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t keyCode, int32_t metaState, bool down, nsecs_t time);
- static void addMetaKeys(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
- int32_t* currentMetaState);
- static bool addSingleEphemeralMetaKey(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
- int32_t keyCode, int32_t keyMetaState,
- int32_t* currentMetaState);
- static void addDoubleEphemeralMetaKey(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
- int32_t leftKeyCode, int32_t leftKeyMetaState,
- int32_t rightKeyCode, int32_t rightKeyMetaState,
- int32_t eitherKeyMetaState,
- int32_t* currentMetaState);
- static void addLockedMetaKey(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t metaState, nsecs_t time,
- int32_t keyCode, int32_t keyMetaState,
- int32_t* currentMetaState);
-};
-
-} // namespace android
-
-#endif // _UI_KEY_CHARACTER_MAP_H
diff --git a/include/ui/KeyLayoutMap.h b/include/ui/KeyLayoutMap.h
deleted file mode 100644
index d82d0c8..0000000
--- a/include/ui/KeyLayoutMap.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_KEY_LAYOUT_MAP_H
-#define _UI_KEY_LAYOUT_MAP_H
-
-#include <stdint.h>
-#include <utils/Errors.h>
-#include <utils/KeyedVector.h>
-#include <utils/Tokenizer.h>
-
-namespace android {
-
-struct AxisInfo {
- enum Mode {
- // Axis value is reported directly.
- MODE_NORMAL = 0,
- // Axis value should be inverted before reporting.
- MODE_INVERT = 1,
- // Axis value should be split into two axes
- MODE_SPLIT = 2,
- };
-
- // Axis mode.
- Mode mode;
-
- // Axis id.
- // When split, this is the axis used for values smaller than the split position.
- int32_t axis;
-
- // When split, this is the axis used for values after higher than the split position.
- int32_t highAxis;
-
- // The split value, or 0 if not split.
- int32_t splitValue;
-
- // The flat value, or -1 if none.
- int32_t flatOverride;
-
- AxisInfo() : mode(MODE_NORMAL), axis(-1), highAxis(-1), splitValue(0), flatOverride(-1) {
- }
-};
-
-/**
- * Describes a mapping from keyboard scan codes and joystick axes to Android key codes and axes.
- */
-class KeyLayoutMap {
-public:
- ~KeyLayoutMap();
-
- static status_t load(const String8& filename, KeyLayoutMap** outMap);
-
- status_t mapKey(int32_t scanCode, int32_t* keyCode, uint32_t* flags) const;
- status_t findScanCodesForKey(int32_t keyCode, Vector<int32_t>* outScanCodes) const;
-
- status_t mapAxis(int32_t scanCode, AxisInfo* outAxisInfo) const;
-
-private:
- struct Key {
- int32_t keyCode;
- uint32_t flags;
- };
-
- KeyedVector<int32_t, Key> mKeys;
- KeyedVector<int32_t, AxisInfo> mAxes;
-
- KeyLayoutMap();
-
- class Parser {
- KeyLayoutMap* mMap;
- Tokenizer* mTokenizer;
-
- public:
- Parser(KeyLayoutMap* map, Tokenizer* tokenizer);
- ~Parser();
- status_t parse();
-
- private:
- status_t parseKey();
- status_t parseAxis();
- };
-};
-
-} // namespace android
-
-#endif // _UI_KEY_LAYOUT_MAP_H
diff --git a/include/ui/Keyboard.h b/include/ui/Keyboard.h
deleted file mode 100644
index 274f526..0000000
--- a/include/ui/Keyboard.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_KEYBOARD_H
-#define _UI_KEYBOARD_H
-
-#include <ui/Input.h>
-#include <utils/Errors.h>
-#include <utils/String8.h>
-#include <utils/PropertyMap.h>
-
-namespace android {
-
-enum {
- /* Device id of the built in keyboard. */
- DEVICE_ID_BUILT_IN_KEYBOARD = 0,
-
- /* Device id of a generic virtual keyboard with a full layout that can be used
- * to synthesize key events. */
- DEVICE_ID_VIRTUAL_KEYBOARD = -1,
-};
-
-class KeyLayoutMap;
-class KeyCharacterMap;
-
-/**
- * Loads the key layout map and key character map for a keyboard device.
- */
-class KeyMap {
-public:
- String8 keyLayoutFile;
- KeyLayoutMap* keyLayoutMap;
-
- String8 keyCharacterMapFile;
- KeyCharacterMap* keyCharacterMap;
-
- KeyMap();
- ~KeyMap();
-
- status_t load(const InputDeviceIdentifier& deviceIdenfier,
- const PropertyMap* deviceConfiguration);
-
- inline bool haveKeyLayout() const {
- return !keyLayoutFile.isEmpty();
- }
-
- inline bool haveKeyCharacterMap() const {
- return !keyCharacterMapFile.isEmpty();
- }
-
- inline bool isComplete() const {
- return haveKeyLayout() && haveKeyCharacterMap();
- }
-
-private:
- bool probeKeyMap(const InputDeviceIdentifier& deviceIdentifier, const String8& name);
- status_t loadKeyLayout(const InputDeviceIdentifier& deviceIdentifier, const String8& name);
- status_t loadKeyCharacterMap(const InputDeviceIdentifier& deviceIdentifier,
- const String8& name);
- String8 getPath(const InputDeviceIdentifier& deviceIdentifier,
- const String8& name, InputDeviceConfigurationFileType type);
-};
-
-/**
- * Returns true if the keyboard is eligible for use as a built-in keyboard.
- */
-extern bool isEligibleBuiltInKeyboard(const InputDeviceIdentifier& deviceIdentifier,
- const PropertyMap* deviceConfiguration, const KeyMap* keyMap);
-
-/**
- * Gets a key code by its short form label, eg. "HOME".
- * Returns 0 if unknown.
- */
-extern int32_t getKeyCodeByLabel(const char* label);
-
-/**
- * Gets a key flag by its short form label, eg. "WAKE".
- * Returns 0 if unknown.
- */
-extern uint32_t getKeyFlagByLabel(const char* label);
-
-/**
- * Gets a axis by its short form label, eg. "X".
- * Returns -1 if unknown.
- */
-extern int32_t getAxisByLabel(const char* label);
-
-/**
- * Gets a axis label by its id.
- * Returns NULL if unknown.
- */
-extern const char* getAxisLabel(int32_t axisId);
-
-/**
- * Updates a meta state field when a key is pressed or released.
- */
-extern int32_t updateMetaState(int32_t keyCode, bool down, int32_t oldMetaState);
-
-/**
- * Returns true if a key is a meta key like ALT or CAPS_LOCK.
- */
-extern bool isMetaKey(int32_t keyCode);
-
-} // namespace android
-
-#endif // _UI_KEYBOARD_H
diff --git a/include/ui/KeycodeLabels.h b/include/ui/KeycodeLabels.h
deleted file mode 100755
index c5bd0c5..0000000
--- a/include/ui/KeycodeLabels.h
+++ /dev/null
@@ -1,310 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_KEYCODE_LABELS_H
-#define _UI_KEYCODE_LABELS_H
-
-#include <android/keycodes.h>
-
-struct KeycodeLabel {
- const char *literal;
- int value;
-};
-
-static const KeycodeLabel KEYCODES[] = {
- { "SOFT_LEFT", 1 },
- { "SOFT_RIGHT", 2 },
- { "HOME", 3 },
- { "BACK", 4 },
- { "CALL", 5 },
- { "ENDCALL", 6 },
- { "0", 7 },
- { "1", 8 },
- { "2", 9 },
- { "3", 10 },
- { "4", 11 },
- { "5", 12 },
- { "6", 13 },
- { "7", 14 },
- { "8", 15 },
- { "9", 16 },
- { "STAR", 17 },
- { "POUND", 18 },
- { "DPAD_UP", 19 },
- { "DPAD_DOWN", 20 },
- { "DPAD_LEFT", 21 },
- { "DPAD_RIGHT", 22 },
- { "DPAD_CENTER", 23 },
- { "VOLUME_UP", 24 },
- { "VOLUME_DOWN", 25 },
- { "POWER", 26 },
- { "CAMERA", 27 },
- { "CLEAR", 28 },
- { "A", 29 },
- { "B", 30 },
- { "C", 31 },
- { "D", 32 },
- { "E", 33 },
- { "F", 34 },
- { "G", 35 },
- { "H", 36 },
- { "I", 37 },
- { "J", 38 },
- { "K", 39 },
- { "L", 40 },
- { "M", 41 },
- { "N", 42 },
- { "O", 43 },
- { "P", 44 },
- { "Q", 45 },
- { "R", 46 },
- { "S", 47 },
- { "T", 48 },
- { "U", 49 },
- { "V", 50 },
- { "W", 51 },
- { "X", 52 },
- { "Y", 53 },
- { "Z", 54 },
- { "COMMA", 55 },
- { "PERIOD", 56 },
- { "ALT_LEFT", 57 },
- { "ALT_RIGHT", 58 },
- { "SHIFT_LEFT", 59 },
- { "SHIFT_RIGHT", 60 },
- { "TAB", 61 },
- { "SPACE", 62 },
- { "SYM", 63 },
- { "EXPLORER", 64 },
- { "ENVELOPE", 65 },
- { "ENTER", 66 },
- { "DEL", 67 },
- { "GRAVE", 68 },
- { "MINUS", 69 },
- { "EQUALS", 70 },
- { "LEFT_BRACKET", 71 },
- { "RIGHT_BRACKET", 72 },
- { "BACKSLASH", 73 },
- { "SEMICOLON", 74 },
- { "APOSTROPHE", 75 },
- { "SLASH", 76 },
- { "AT", 77 },
- { "NUM", 78 },
- { "HEADSETHOOK", 79 },
- { "FOCUS", 80 },
- { "PLUS", 81 },
- { "MENU", 82 },
- { "NOTIFICATION", 83 },
- { "SEARCH", 84 },
- { "MEDIA_PLAY_PAUSE", 85 },
- { "MEDIA_STOP", 86 },
- { "MEDIA_NEXT", 87 },
- { "MEDIA_PREVIOUS", 88 },
- { "MEDIA_REWIND", 89 },
- { "MEDIA_FAST_FORWARD", 90 },
- { "MUTE", 91 },
- { "PAGE_UP", 92 },
- { "PAGE_DOWN", 93 },
- { "PICTSYMBOLS", 94 },
- { "SWITCH_CHARSET", 95 },
- { "BUTTON_A", 96 },
- { "BUTTON_B", 97 },
- { "BUTTON_C", 98 },
- { "BUTTON_X", 99 },
- { "BUTTON_Y", 100 },
- { "BUTTON_Z", 101 },
- { "BUTTON_L1", 102 },
- { "BUTTON_R1", 103 },
- { "BUTTON_L2", 104 },
- { "BUTTON_R2", 105 },
- { "BUTTON_THUMBL", 106 },
- { "BUTTON_THUMBR", 107 },
- { "BUTTON_START", 108 },
- { "BUTTON_SELECT", 109 },
- { "BUTTON_MODE", 110 },
- { "ESCAPE", 111 },
- { "FORWARD_DEL", 112 },
- { "CTRL_LEFT", 113 },
- { "CTRL_RIGHT", 114 },
- { "CAPS_LOCK", 115 },
- { "SCROLL_LOCK", 116 },
- { "META_LEFT", 117 },
- { "META_RIGHT", 118 },
- { "FUNCTION", 119 },
- { "SYSRQ", 120 },
- { "BREAK", 121 },
- { "MOVE_HOME", 122 },
- { "MOVE_END", 123 },
- { "INSERT", 124 },
- { "FORWARD", 125 },
- { "MEDIA_PLAY", 126 },
- { "MEDIA_PAUSE", 127 },
- { "MEDIA_CLOSE", 128 },
- { "MEDIA_EJECT", 129 },
- { "MEDIA_RECORD", 130 },
- { "F1", 131 },
- { "F2", 132 },
- { "F3", 133 },
- { "F4", 134 },
- { "F5", 135 },
- { "F6", 136 },
- { "F7", 137 },
- { "F8", 138 },
- { "F9", 139 },
- { "F10", 140 },
- { "F11", 141 },
- { "F12", 142 },
- { "NUM_LOCK", 143 },
- { "NUMPAD_0", 144 },
- { "NUMPAD_1", 145 },
- { "NUMPAD_2", 146 },
- { "NUMPAD_3", 147 },
- { "NUMPAD_4", 148 },
- { "NUMPAD_5", 149 },
- { "NUMPAD_6", 150 },
- { "NUMPAD_7", 151 },
- { "NUMPAD_8", 152 },
- { "NUMPAD_9", 153 },
- { "NUMPAD_DIVIDE", 154 },
- { "NUMPAD_MULTIPLY", 155 },
- { "NUMPAD_SUBTRACT", 156 },
- { "NUMPAD_ADD", 157 },
- { "NUMPAD_DOT", 158 },
- { "NUMPAD_COMMA", 159 },
- { "NUMPAD_ENTER", 160 },
- { "NUMPAD_EQUALS", 161 },
- { "NUMPAD_LEFT_PAREN", 162 },
- { "NUMPAD_RIGHT_PAREN", 163 },
- { "VOLUME_MUTE", 164 },
- { "INFO", 165 },
- { "CHANNEL_UP", 166 },
- { "CHANNEL_DOWN", 167 },
- { "ZOOM_IN", 168 },
- { "ZOOM_OUT", 169 },
- { "TV", 170 },
- { "WINDOW", 171 },
- { "GUIDE", 172 },
- { "DVR", 173 },
- { "BOOKMARK", 174 },
- { "CAPTIONS", 175 },
- { "SETTINGS", 176 },
- { "TV_POWER", 177 },
- { "TV_INPUT", 178 },
- { "STB_POWER", 179 },
- { "STB_INPUT", 180 },
- { "AVR_POWER", 181 },
- { "AVR_INPUT", 182 },
- { "PROG_RED", 183 },
- { "PROG_GREEN", 184 },
- { "PROG_YELLOW", 185 },
- { "PROG_BLUE", 186 },
- { "APP_SWITCH", 187 },
- { "BUTTON_1", 188 },
- { "BUTTON_2", 189 },
- { "BUTTON_3", 190 },
- { "BUTTON_4", 191 },
- { "BUTTON_5", 192 },
- { "BUTTON_6", 193 },
- { "BUTTON_7", 194 },
- { "BUTTON_8", 195 },
- { "BUTTON_9", 196 },
- { "BUTTON_10", 197 },
- { "BUTTON_11", 198 },
- { "BUTTON_12", 199 },
- { "BUTTON_13", 200 },
- { "BUTTON_14", 201 },
- { "BUTTON_15", 202 },
- { "BUTTON_16", 203 },
- { "LANGUAGE_SWITCH", 204 },
- { "MANNER_MODE", 205 },
- { "3D_MODE", 206 },
- { "CONTACTS", 207 },
- { "CALENDAR", 208 },
- { "MUSIC", 209 },
- { "CALCULATOR", 210 },
-
- // NOTE: If you add a new keycode here you must also add it to several other files.
- // Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
-
- { NULL, 0 }
-};
-
-// NOTE: If you edit these flags, also edit policy flags in Input.h.
-static const KeycodeLabel FLAGS[] = {
- { "WAKE", 0x00000001 },
- { "WAKE_DROPPED", 0x00000002 },
- { "SHIFT", 0x00000004 },
- { "CAPS_LOCK", 0x00000008 },
- { "ALT", 0x00000010 },
- { "ALT_GR", 0x00000020 },
- { "MENU", 0x00000040 },
- { "LAUNCHER", 0x00000080 },
- { "VIRTUAL", 0x00000100 },
- { "FUNCTION", 0x00000200 },
- { NULL, 0 }
-};
-
-static const KeycodeLabel AXES[] = {
- { "X", 0 },
- { "Y", 1 },
- { "PRESSURE", 2 },
- { "SIZE", 3 },
- { "TOUCH_MAJOR", 4 },
- { "TOUCH_MINOR", 5 },
- { "TOOL_MAJOR", 6 },
- { "TOOL_MINOR", 7 },
- { "ORIENTATION", 8 },
- { "VSCROLL", 9 },
- { "HSCROLL", 10 },
- { "Z", 11 },
- { "RX", 12 },
- { "RY", 13 },
- { "RZ", 14 },
- { "HAT_X", 15 },
- { "HAT_Y", 16 },
- { "LTRIGGER", 17 },
- { "RTRIGGER", 18 },
- { "THROTTLE", 19 },
- { "RUDDER", 20 },
- { "WHEEL", 21 },
- { "GAS", 22 },
- { "BRAKE", 23 },
- { "DISTANCE", 24 },
- { "TILT", 25 },
- { "GENERIC_1", 32 },
- { "GENERIC_2", 33 },
- { "GENERIC_3", 34 },
- { "GENERIC_4", 35 },
- { "GENERIC_5", 36 },
- { "GENERIC_6", 37 },
- { "GENERIC_7", 38 },
- { "GENERIC_8", 39 },
- { "GENERIC_9", 40 },
- { "GENERIC_10", 41 },
- { "GENERIC_11", 42 },
- { "GENERIC_12", 43 },
- { "GENERIC_13", 44 },
- { "GENERIC_14", 45 },
- { "GENERIC_15", 46 },
- { "GENERIC_16", 47 },
-
- // NOTE: If you add a new axis here you must also add it to several other files.
- // Refer to frameworks/base/core/java/android/view/MotionEvent.java for the full list.
-
- { NULL, -1 }
-};
-
-#endif // _UI_KEYCODE_LABELS_H
diff --git a/include/ui/PixelFormat.h b/include/ui/PixelFormat.h
index 848c5a1..fc260c4 100644
--- a/include/ui/PixelFormat.h
+++ b/include/ui/PixelFormat.h
@@ -21,7 +21,6 @@
// skia or SurfaceFlinger are not required to support all of these formats
// (either as source or destination)
-// XXX: we should consolidate these formats and skia's
#ifndef UI_PIXELFORMAT_H
#define UI_PIXELFORMAT_H
@@ -29,7 +28,6 @@
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
-#include <pixelflinger/format.h>
#include <hardware/hardware.h>
namespace android {
@@ -65,10 +63,7 @@ enum {
PIXEL_FORMAT_BGRA_8888 = HAL_PIXEL_FORMAT_BGRA_8888, // 4x8-bit BGRA
PIXEL_FORMAT_RGBA_5551 = HAL_PIXEL_FORMAT_RGBA_5551, // 16-bit ARGB
PIXEL_FORMAT_RGBA_4444 = HAL_PIXEL_FORMAT_RGBA_4444, // 16-bit ARGB
- PIXEL_FORMAT_A_8 = GGL_PIXEL_FORMAT_A_8, // 8-bit A
- PIXEL_FORMAT_L_8 = GGL_PIXEL_FORMAT_L_8, // 8-bit L (R=G=B=L)
- PIXEL_FORMAT_LA_88 = GGL_PIXEL_FORMAT_LA_88, // 16-bit LA
- PIXEL_FORMAT_RGB_332 = GGL_PIXEL_FORMAT_RGB_332, // 8-bit RGB
+ PIXEL_FORMAT_A_8 = 8, // 8-bit A
// New formats can be added if they're also defined in
// pixelflinger/format.h
@@ -76,8 +71,7 @@ enum {
typedef int32_t PixelFormat;
-struct PixelFormatInfo
-{
+struct PixelFormatInfo {
enum {
INDEX_ALPHA = 0,
INDEX_RED = 1,
@@ -89,8 +83,6 @@ struct PixelFormatInfo
ALPHA = 1,
RGB = 2,
RGBA = 3,
- LUMINANCE = 4,
- LUMINANCE_ALPHA = 5,
OTHER = 0xFF
};
diff --git a/include/ui/PowerManager.h b/include/ui/PowerManager.h
deleted file mode 100644
index dd80318..0000000
--- a/include/ui/PowerManager.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_POWER_MANAGER_H
-#define _UI_POWER_MANAGER_H
-
-
-namespace android {
-
-enum {
- POWER_MANAGER_OTHER_EVENT = 0,
- POWER_MANAGER_BUTTON_EVENT = 1,
- POWER_MANAGER_TOUCH_EVENT = 2,
-
- POWER_MANAGER_LAST_EVENT = POWER_MANAGER_TOUCH_EVENT, // Last valid event code.
-};
-
-} // namespace android
-
-#endif // _UI_POWER_MANAGER_H
diff --git a/include/ui/Region.h b/include/ui/Region.h
index 6c9a620..f242f18 100644
--- a/include/ui/Region.h
+++ b/include/ui/Region.h
@@ -55,43 +55,51 @@ public:
void set(uint32_t w, uint32_t h);
Region& orSelf(const Rect& rhs);
+ Region& xorSelf(const Rect& rhs);
Region& andSelf(const Rect& rhs);
Region& subtractSelf(const Rect& rhs);
// boolean operators, applied on this
Region& orSelf(const Region& rhs);
+ Region& xorSelf(const Region& rhs);
Region& andSelf(const Region& rhs);
Region& subtractSelf(const Region& rhs);
// boolean operators
const Region merge(const Rect& rhs) const;
+ const Region mergeExclusive(const Rect& rhs) const;
const Region intersect(const Rect& rhs) const;
const Region subtract(const Rect& rhs) const;
// boolean operators
const Region merge(const Region& rhs) const;
+ const Region mergeExclusive(const Region& rhs) const;
const Region intersect(const Region& rhs) const;
const Region subtract(const Region& rhs) const;
// these translate rhs first
Region& translateSelf(int dx, int dy);
Region& orSelf(const Region& rhs, int dx, int dy);
+ Region& xorSelf(const Region& rhs, int dx, int dy);
Region& andSelf(const Region& rhs, int dx, int dy);
Region& subtractSelf(const Region& rhs, int dx, int dy);
// these translate rhs first
const Region translate(int dx, int dy) const;
const Region merge(const Region& rhs, int dx, int dy) const;
+ const Region mergeExclusive(const Region& rhs, int dx, int dy) const;
const Region intersect(const Region& rhs, int dx, int dy) const;
const Region subtract(const Region& rhs, int dx, int dy) const;
// convenience operators overloads
inline const Region operator | (const Region& rhs) const;
+ inline const Region operator ^ (const Region& rhs) const;
inline const Region operator & (const Region& rhs) const;
inline const Region operator - (const Region& rhs) const;
inline const Region operator + (const Point& pt) const;
inline Region& operator |= (const Region& rhs);
+ inline Region& operator ^= (const Region& rhs);
inline Region& operator &= (const Region& rhs);
inline Region& operator -= (const Region& rhs);
inline Region& operator += (const Point& pt);
@@ -158,6 +166,9 @@ private:
const Region Region::operator | (const Region& rhs) const {
return merge(rhs);
}
+const Region Region::operator ^ (const Region& rhs) const {
+ return mergeExclusive(rhs);
+}
const Region Region::operator & (const Region& rhs) const {
return intersect(rhs);
}
@@ -172,6 +183,9 @@ const Region Region::operator + (const Point& pt) const {
Region& Region::operator |= (const Region& rhs) {
return orSelf(rhs);
}
+Region& Region::operator ^= (const Region& rhs) {
+ return xorSelf(rhs);
+}
Region& Region::operator &= (const Region& rhs) {
return andSelf(rhs);
}
diff --git a/include/ui/VirtualKeyMap.h b/include/ui/VirtualKeyMap.h
deleted file mode 100644
index 7813d9d..0000000
--- a/include/ui/VirtualKeyMap.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_VIRTUAL_KEY_MAP_H
-#define _UI_VIRTUAL_KEY_MAP_H
-
-#include <stdint.h>
-
-#include <ui/Input.h>
-#include <utils/Errors.h>
-#include <utils/KeyedVector.h>
-#include <utils/Tokenizer.h>
-#include <utils/String8.h>
-#include <utils/Unicode.h>
-
-namespace android {
-
-/* Describes a virtual key. */
-struct VirtualKeyDefinition {
- int32_t scanCode;
-
- // configured position data, specified in display coords
- int32_t centerX;
- int32_t centerY;
- int32_t width;
- int32_t height;
-};
-
-
-/**
- * Describes a collection of virtual keys on a touch screen in terms of
- * virtual scan codes and hit rectangles.
- */
-class VirtualKeyMap {
-public:
- ~VirtualKeyMap();
-
- static status_t load(const String8& filename, VirtualKeyMap** outMap);
-
- inline const Vector<VirtualKeyDefinition>& getVirtualKeys() const {
- return mVirtualKeys;
- }
-
-private:
- class Parser {
- VirtualKeyMap* mMap;
- Tokenizer* mTokenizer;
-
- public:
- Parser(VirtualKeyMap* map, Tokenizer* tokenizer);
- ~Parser();
- status_t parse();
-
- private:
- bool consumeFieldDelimiterAndSkipWhitespace();
- bool parseNextIntField(int32_t* outValue);
- };
-
- Vector<VirtualKeyDefinition> mVirtualKeys;
-
- VirtualKeyMap();
-};
-
-} // namespace android
-
-#endif // _UI_KEY_CHARACTER_MAP_H
diff --git a/include/utils/Asset.h b/include/utils/Asset.h
deleted file mode 100644
index 1fe0e06..0000000
--- a/include/utils/Asset.h
+++ /dev/null
@@ -1,322 +0,0 @@
-/*
- * Copyright (C) 2006 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//
-// Class providing access to a read-only asset. Asset objects are NOT
-// thread-safe, and should not be shared across threads.
-//
-#ifndef __LIBS_ASSET_H
-#define __LIBS_ASSET_H
-
-#include <stdio.h>
-#include <sys/types.h>
-
-#include <utils/Compat.h>
-#include <utils/Errors.h>
-#include <utils/FileMap.h>
-#include <utils/String8.h>
-
-namespace android {
-
-/*
- * Instances of this class provide read-only operations on a byte stream.
- *
- * Access may be optimized for streaming, random, or whole buffer modes. All
- * operations are supported regardless of how the file was opened, but some
- * things will be less efficient. [pass that in??]
- *
- * "Asset" is the base class for all types of assets. The classes below
- * provide most of the implementation. The AssetManager uses one of the
- * static "create" functions defined here to create a new instance.
- */
-class Asset {
-public:
- virtual ~Asset(void);
-
- static int32_t getGlobalCount();
- static String8 getAssetAllocations();
-
- /* used when opening an asset */
- typedef enum AccessMode {
- ACCESS_UNKNOWN = 0,
-
- /* read chunks, and seek forward and backward */
- ACCESS_RANDOM,
-
- /* read sequentially, with an occasional forward seek */
- ACCESS_STREAMING,
-
- /* caller plans to ask for a read-only buffer with all data */
- ACCESS_BUFFER,
- } AccessMode;
-
- /*
- * Read data from the current offset. Returns the actual number of
- * bytes read, 0 on EOF, or -1 on error.
- */
- virtual ssize_t read(void* buf, size_t count) = 0;
-
- /*
- * Seek to the specified offset. "whence" uses the same values as
- * lseek/fseek. Returns the new position on success, or (off64_t) -1
- * on failure.
- */
- virtual off64_t seek(off64_t offset, int whence) = 0;
-
- /*
- * Close the asset, freeing all associated resources.
- */
- virtual void close(void) = 0;
-
- /*
- * Get a pointer to a buffer with the entire contents of the file.
- */
- virtual const void* getBuffer(bool wordAligned) = 0;
-
- /*
- * Get the total amount of data that can be read.
- */
- virtual off64_t getLength(void) const = 0;
-
- /*
- * Get the total amount of data that can be read from the current position.
- */
- virtual off64_t getRemainingLength(void) const = 0;
-
- /*
- * Open a new file descriptor that can be used to read this asset.
- * Returns -1 if you can not use the file descriptor (for example if the
- * asset is compressed).
- */
- virtual int openFileDescriptor(off64_t* outStart, off64_t* outLength) const = 0;
-
- /*
- * Return whether this asset's buffer is allocated in RAM (not mmapped).
- * Note: not virtual so it is safe to call even when being destroyed.
- */
- virtual bool isAllocated(void) const { return false; }
-
- /*
- * Get a string identifying the asset's source. This might be a full
- * path, it might be a colon-separated list of identifiers.
- *
- * This is NOT intended to be used for anything except debug output.
- * DO NOT try to parse this or use it to open a file.
- */
- const char* getAssetSource(void) const { return mAssetSource.string(); }
-
-protected:
- Asset(void); // constructor; only invoked indirectly
-
- /* handle common seek() housekeeping */
- off64_t handleSeek(off64_t offset, int whence, off64_t curPosn, off64_t maxPosn);
-
- /* set the asset source string */
- void setAssetSource(const String8& path) { mAssetSource = path; }
-
- AccessMode getAccessMode(void) const { return mAccessMode; }
-
-private:
- /* these operations are not implemented */
- Asset(const Asset& src);
- Asset& operator=(const Asset& src);
-
- /* AssetManager needs access to our "create" functions */
- friend class AssetManager;
-
- /*
- * Create the asset from a named file on disk.
- */
- static Asset* createFromFile(const char* fileName, AccessMode mode);
-
- /*
- * Create the asset from a named, compressed file on disk (e.g. ".gz").
- */
- static Asset* createFromCompressedFile(const char* fileName,
- AccessMode mode);
-
-#if 0
- /*
- * Create the asset from a segment of an open file. This will fail
- * if "offset" and "length" don't fit within the bounds of the file.
- *
- * The asset takes ownership of the file descriptor.
- */
- static Asset* createFromFileSegment(int fd, off64_t offset, size_t length,
- AccessMode mode);
-
- /*
- * Create from compressed data. "fd" should be seeked to the start of
- * the compressed data. This could be inside a gzip file or part of a
- * Zip archive.
- *
- * The asset takes ownership of the file descriptor.
- *
- * This may not verify the validity of the compressed data until first
- * use.
- */
- static Asset* createFromCompressedData(int fd, off64_t offset,
- int compressionMethod, size_t compressedLength,
- size_t uncompressedLength, AccessMode mode);
-#endif
-
- /*
- * Create the asset from a memory-mapped file segment.
- *
- * The asset takes ownership of the FileMap.
- */
- static Asset* createFromUncompressedMap(FileMap* dataMap, AccessMode mode);
-
- /*
- * Create the asset from a memory-mapped file segment with compressed
- * data. "method" is a Zip archive compression method constant.
- *
- * The asset takes ownership of the FileMap.
- */
- static Asset* createFromCompressedMap(FileMap* dataMap, int method,
- size_t uncompressedLen, AccessMode mode);
-
-
- /*
- * Create from a reference-counted chunk of shared memory.
- */
- // TODO
-
- AccessMode mAccessMode; // how the asset was opened
- String8 mAssetSource; // debug string
-
- Asset* mNext; // linked list.
- Asset* mPrev;
-};
-
-
-/*
- * ===========================================================================
- *
- * Innards follow. Do not use these classes directly.
- */
-
-/*
- * An asset based on an uncompressed file on disk. It may encompass the
- * entire file or just a piece of it. Access is through fread/fseek.
- */
-class _FileAsset : public Asset {
-public:
- _FileAsset(void);
- virtual ~_FileAsset(void);
-
- /*
- * Use a piece of an already-open file.
- *
- * On success, the object takes ownership of "fd".
- */
- status_t openChunk(const char* fileName, int fd, off64_t offset, size_t length);
-
- /*
- * Use a memory-mapped region.
- *
- * On success, the object takes ownership of "dataMap".
- */
- status_t openChunk(FileMap* dataMap);
-
- /*
- * Standard Asset interfaces.
- */
- virtual ssize_t read(void* buf, size_t count);
- virtual off64_t seek(off64_t offset, int whence);
- virtual void close(void);
- virtual const void* getBuffer(bool wordAligned);
- virtual off64_t getLength(void) const { return mLength; }
- virtual off64_t getRemainingLength(void) const { return mLength-mOffset; }
- virtual int openFileDescriptor(off64_t* outStart, off64_t* outLength) const;
- virtual bool isAllocated(void) const { return mBuf != NULL; }
-
-private:
- off64_t mStart; // absolute file offset of start of chunk
- off64_t mLength; // length of the chunk
- off64_t mOffset; // current local offset, 0 == mStart
- FILE* mFp; // for read/seek
- char* mFileName; // for opening
-
- /*
- * To support getBuffer() we either need to read the entire thing into
- * a buffer or memory-map it. For small files it's probably best to
- * just read them in.
- */
- enum { kReadVsMapThreshold = 4096 };
-
- FileMap* mMap; // for memory map
- unsigned char* mBuf; // for read
-
- const void* ensureAlignment(FileMap* map);
-};
-
-
-/*
- * An asset based on compressed data in a file.
- */
-class _CompressedAsset : public Asset {
-public:
- _CompressedAsset(void);
- virtual ~_CompressedAsset(void);
-
- /*
- * Use a piece of an already-open file.
- *
- * On success, the object takes ownership of "fd".
- */
- status_t openChunk(int fd, off64_t offset, int compressionMethod,
- size_t uncompressedLen, size_t compressedLen);
-
- /*
- * Use a memory-mapped region.
- *
- * On success, the object takes ownership of "fd".
- */
- status_t openChunk(FileMap* dataMap, int compressionMethod,
- size_t uncompressedLen);
-
- /*
- * Standard Asset interfaces.
- */
- virtual ssize_t read(void* buf, size_t count);
- virtual off64_t seek(off64_t offset, int whence);
- virtual void close(void);
- virtual const void* getBuffer(bool wordAligned);
- virtual off64_t getLength(void) const { return mUncompressedLen; }
- virtual off64_t getRemainingLength(void) const { return mUncompressedLen-mOffset; }
- virtual int openFileDescriptor(off64_t* outStart, off64_t* outLength) const { return -1; }
- virtual bool isAllocated(void) const { return mBuf != NULL; }
-
-private:
- off64_t mStart; // offset to start of compressed data
- off64_t mCompressedLen; // length of the compressed data
- off64_t mUncompressedLen; // length of the uncompressed data
- off64_t mOffset; // current offset, 0 == start of uncomp data
-
- FileMap* mMap; // for memory-mapped input
- int mFd; // for file input
-
- class StreamingZipInflater* mZipInflater; // for streaming large compressed assets
-
- unsigned char* mBuf; // for getBuffer()
-};
-
-// need: shared mmap version?
-
-}; // namespace android
-
-#endif // __LIBS_ASSET_H
diff --git a/include/utils/AssetDir.h b/include/utils/AssetDir.h
deleted file mode 100644
index abf8a35..0000000
--- a/include/utils/AssetDir.h
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright (C) 2006 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//
-// Access a chunk of the asset hierarchy as if it were a single directory.
-//
-#ifndef __LIBS_ASSETDIR_H
-#define __LIBS_ASSETDIR_H
-
-#include <utils/String8.h>
-#include <utils/Vector.h>
-#include <utils/SortedVector.h>
-#include <utils/misc.h>
-#include <sys/types.h>
-
-namespace android {
-
-/*
- * This provides vector-style access to a directory. We do this rather
- * than modeling opendir/readdir access because it's simpler and the
- * nature of the operation requires us to have all data on hand anyway.
- *
- * The list of files will be sorted in ascending order by ASCII value.
- *
- * The contents are populated by our friend, the AssetManager.
- */
-class AssetDir {
-public:
- AssetDir(void)
- : mFileInfo(NULL)
- {}
- virtual ~AssetDir(void) {
- delete mFileInfo;
- }
-
- /*
- * Vector-style access.
- */
- size_t getFileCount(void) { return mFileInfo->size(); }
- const String8& getFileName(int idx) {
- return mFileInfo->itemAt(idx).getFileName();
- }
- const String8& getSourceName(int idx) {
- return mFileInfo->itemAt(idx).getSourceName();
- }
-
- /*
- * Get the type of a file (usually regular or directory).
- */
- FileType getFileType(int idx) {
- return mFileInfo->itemAt(idx).getFileType();
- }
-
-private:
- /* these operations are not implemented */
- AssetDir(const AssetDir& src);
- const AssetDir& operator=(const AssetDir& src);
-
- friend class AssetManager;
-
- /*
- * This holds information about files in the asset hierarchy.
- */
- class FileInfo {
- public:
- FileInfo(void) {}
- FileInfo(const String8& path) // useful for e.g. svect.indexOf
- : mFileName(path), mFileType(kFileTypeUnknown)
- {}
- ~FileInfo(void) {}
- FileInfo(const FileInfo& src) {
- copyMembers(src);
- }
- const FileInfo& operator= (const FileInfo& src) {
- if (this != &src)
- copyMembers(src);
- return *this;
- }
-
- void copyMembers(const FileInfo& src) {
- mFileName = src.mFileName;
- mFileType = src.mFileType;
- mSourceName = src.mSourceName;
- }
-
- /* need this for SortedVector; must compare only on file name */
- bool operator< (const FileInfo& rhs) const {
- return mFileName < rhs.mFileName;
- }
-
- /* used by AssetManager */
- bool operator== (const FileInfo& rhs) const {
- return mFileName == rhs.mFileName;
- }
-
- void set(const String8& path, FileType type) {
- mFileName = path;
- mFileType = type;
- }
-
- const String8& getFileName(void) const { return mFileName; }
- void setFileName(const String8& path) { mFileName = path; }
-
- FileType getFileType(void) const { return mFileType; }
- void setFileType(FileType type) { mFileType = type; }
-
- const String8& getSourceName(void) const { return mSourceName; }
- void setSourceName(const String8& path) { mSourceName = path; }
-
- /*
- * Handy utility for finding an entry in a sorted vector of FileInfo.
- * Returns the index of the matching entry, or -1 if none found.
- */
- static int findEntry(const SortedVector<FileInfo>* pVector,
- const String8& fileName);
-
- private:
- String8 mFileName; // filename only
- FileType mFileType; // regular, directory, etc
-
- String8 mSourceName; // currently debug-only
- };
-
- /* AssetManager uses this to initialize us */
- void setFileList(SortedVector<FileInfo>* list) { mFileInfo = list; }
-
- SortedVector<FileInfo>* mFileInfo;
-};
-
-}; // namespace android
-
-#endif // __LIBS_ASSETDIR_H
diff --git a/include/utils/AssetManager.h b/include/utils/AssetManager.h
deleted file mode 100644
index a8c7ddb..0000000
--- a/include/utils/AssetManager.h
+++ /dev/null
@@ -1,373 +0,0 @@
-/*
- * Copyright (C) 2006 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//
-// Asset management class. AssetManager objects are thread-safe.
-//
-#ifndef __LIBS_ASSETMANAGER_H
-#define __LIBS_ASSETMANAGER_H
-
-#include <utils/Asset.h>
-#include <utils/AssetDir.h>
-#include <utils/KeyedVector.h>
-#include <utils/String8.h>
-#include <utils/Vector.h>
-#include <utils/String16.h>
-#include <utils/ZipFileRO.h>
-#include <utils/threads.h>
-
-/*
- * Native-app access is via the opaque typedef struct AAssetManager in the C namespace.
- */
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct AAssetManager { };
-
-#ifdef __cplusplus
-};
-#endif
-
-
-/*
- * Now the proper C++ android-namespace definitions
- */
-
-namespace android {
-
-class Asset; // fwd decl for things that include Asset.h first
-class ResTable;
-struct ResTable_config;
-
-/*
- * Every application that uses assets needs one instance of this. A
- * single instance may be shared across multiple threads, and a single
- * thread may have more than one instance (the latter is discouraged).
- *
- * The purpose of the AssetManager is to create Asset objects. To do
- * this efficiently it may cache information about the locations of
- * files it has seen. This can be controlled with the "cacheMode"
- * argument.
- *
- * The asset hierarchy may be examined like a filesystem, using
- * AssetDir objects to peruse a single directory.
- */
-class AssetManager : public AAssetManager {
-public:
- typedef enum CacheMode {
- CACHE_UNKNOWN = 0,
- CACHE_OFF, // don't try to cache file locations
- CACHE_DEFER, // construct cache as pieces are needed
- //CACHE_SCAN, // scan full(!) asset hierarchy at init() time
- } CacheMode;
-
- AssetManager(CacheMode cacheMode = CACHE_OFF);
- virtual ~AssetManager(void);
-
- static int32_t getGlobalCount();
-
- /*
- * Add a new source for assets. This can be called multiple times to
- * look in multiple places for assets. It can be either a directory (for
- * finding assets as raw files on the disk) or a ZIP file. This newly
- * added asset path will be examined first when searching for assets,
- * before any that were previously added.
- *
- * Returns "true" on success, "false" on failure. If 'cookie' is non-NULL,
- * then on success, *cookie is set to the value corresponding to the
- * newly-added asset source.
- */
- bool addAssetPath(const String8& path, void** cookie);
-
- /*
- * Convenience for adding the standard system assets. Uses the
- * ANDROID_ROOT environment variable to find them.
- */
- bool addDefaultAssets();
-
- /*
- * Iterate over the asset paths in this manager. (Previously
- * added via addAssetPath() and addDefaultAssets().) On first call,
- * 'cookie' must be NULL, resulting in the first cookie being returned.
- * Each next cookie will be returned there-after, until NULL indicating
- * the end has been reached.
- */
- void* nextAssetPath(void* cookie) const;
-
- /*
- * Return an asset path in the manager. 'which' must be between 0 and
- * countAssetPaths().
- */
- String8 getAssetPath(void* cookie) const;
-
- /*
- * Set the current locale and vendor. The locale can change during
- * the lifetime of an AssetManager if the user updates the device's
- * language setting. The vendor is less likely to change.
- *
- * Pass in NULL to indicate no preference.
- */
- void setLocale(const char* locale);
- void setVendor(const char* vendor);
-
- /*
- * Choose screen orientation for resources values returned.
- */
- void setConfiguration(const ResTable_config& config, const char* locale = NULL);
-
- void getConfiguration(ResTable_config* outConfig) const;
-
- typedef Asset::AccessMode AccessMode; // typing shortcut
-
- /*
- * Open an asset.
- *
- * This will search through locale-specific and vendor-specific
- * directories and packages to find the file.
- *
- * The object returned does not depend on the AssetManager. It should
- * be freed by calling Asset::close().
- */
- Asset* open(const char* fileName, AccessMode mode);
-
- /*
- * Open a non-asset file as an asset.
- *
- * This is for opening files that are included in an asset package
- * but aren't assets. These sit outside the usual "locale/vendor"
- * path hierarchy, and will not be seen by "AssetDir" or included
- * in our filename cache.
- */
- Asset* openNonAsset(const char* fileName, AccessMode mode);
-
- /*
- * Explicit non-asset file. The file explicitly named by the cookie (the
- * resource set to look in) and fileName will be opened and returned.
- */
- Asset* openNonAsset(void* cookie, const char* fileName, AccessMode mode);
-
- /*
- * Open a directory within the asset hierarchy.
- *
- * The contents of the directory are an amalgam of vendor-specific,
- * locale-specific, and generic assets stored loosely or in asset
- * packages. Depending on the cache setting and previous accesses,
- * this call may incur significant disk overhead.
- *
- * To open the top-level directory, pass in "".
- */
- AssetDir* openDir(const char* dirName);
-
- /*
- * Open a directory within a particular path of the asset manager.
- *
- * The contents of the directory are an amalgam of vendor-specific,
- * locale-specific, and generic assets stored loosely or in asset
- * packages. Depending on the cache setting and previous accesses,
- * this call may incur significant disk overhead.
- *
- * To open the top-level directory, pass in "".
- */
- AssetDir* openNonAssetDir(void* cookie, const char* dirName);
-
- /*
- * Get the type of a file in the asset hierarchy. They will either
- * be "regular" or "directory". [Currently only works for "regular".]
- *
- * Can also be used as a quick test for existence of a file.
- */
- FileType getFileType(const char* fileName);
-
- /*
- * Return the complete resource table to find things in the package.
- */
- const ResTable& getResources(bool required = true) const;
-
- /*
- * Discard cached filename information. This only needs to be called
- * if somebody has updated the set of "loose" files, and we want to
- * discard our cached notion of what's where.
- */
- void purge(void) { purgeFileNameCacheLocked(); }
-
- /*
- * Return true if the files this AssetManager references are all
- * up-to-date (have not been changed since it was created). If false
- * is returned, you will need to create a new AssetManager to get
- * the current data.
- */
- bool isUpToDate();
-
- /**
- * Get the known locales for this asset manager object.
- */
- void getLocales(Vector<String8>* locales) const;
-
-private:
- struct asset_path
- {
- String8 path;
- FileType type;
- String8 idmap;
- };
-
- Asset* openInPathLocked(const char* fileName, AccessMode mode,
- const asset_path& path);
- Asset* openNonAssetInPathLocked(const char* fileName, AccessMode mode,
- const asset_path& path);
- Asset* openInLocaleVendorLocked(const char* fileName, AccessMode mode,
- const asset_path& path, const char* locale, const char* vendor);
- String8 createPathNameLocked(const asset_path& path, const char* locale,
- const char* vendor);
- String8 createPathNameLocked(const asset_path& path, const char* rootDir);
- String8 createZipSourceNameLocked(const String8& zipFileName,
- const String8& dirName, const String8& fileName);
-
- ZipFileRO* getZipFileLocked(const asset_path& path);
- Asset* openAssetFromFileLocked(const String8& fileName, AccessMode mode);
- Asset* openAssetFromZipLocked(const ZipFileRO* pZipFile,
- const ZipEntryRO entry, AccessMode mode, const String8& entryName);
-
- bool scanAndMergeDirLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
- const asset_path& path, const char* rootDir, const char* dirName);
- SortedVector<AssetDir::FileInfo>* scanDirLocked(const String8& path);
- bool scanAndMergeZipLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
- const asset_path& path, const char* rootDir, const char* dirName);
- void mergeInfoLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
- const SortedVector<AssetDir::FileInfo>* pContents);
-
- void loadFileNameCacheLocked(void);
- void fncScanLocked(SortedVector<AssetDir::FileInfo>* pMergedInfo,
- const char* dirName);
- bool fncScanAndMergeDirLocked(
- SortedVector<AssetDir::FileInfo>* pMergedInfo,
- const asset_path& path, const char* locale, const char* vendor,
- const char* dirName);
- void purgeFileNameCacheLocked(void);
-
- const ResTable* getResTable(bool required = true) const;
- void setLocaleLocked(const char* locale);
- void updateResourceParamsLocked() const;
-
- bool createIdmapFileLocked(const String8& originalPath, const String8& overlayPath,
- const String8& idmapPath);
-
- bool isIdmapStaleLocked(const String8& originalPath, const String8& overlayPath,
- const String8& idmapPath);
-
- Asset* openIdmapLocked(const struct asset_path& ap) const;
-
- bool getZipEntryCrcLocked(const String8& zipPath, const char* entryFilename, uint32_t* pCrc);
-
- class SharedZip : public RefBase {
- public:
- static sp<SharedZip> get(const String8& path);
-
- ZipFileRO* getZip();
-
- Asset* getResourceTableAsset();
- Asset* setResourceTableAsset(Asset* asset);
-
- ResTable* getResourceTable();
- ResTable* setResourceTable(ResTable* res);
-
- bool isUpToDate();
-
- protected:
- ~SharedZip();
-
- private:
- SharedZip(const String8& path, time_t modWhen);
- SharedZip(); // <-- not implemented
-
- String8 mPath;
- ZipFileRO* mZipFile;
- time_t mModWhen;
-
- Asset* mResourceTableAsset;
- ResTable* mResourceTable;
-
- static Mutex gLock;
- static DefaultKeyedVector<String8, wp<SharedZip> > gOpen;
- };
-
- /*
- * Manage a set of Zip files. For each file we need a pointer to the
- * ZipFile and a time_t with the file's modification date.
- *
- * We currently only have two zip files (current app, "common" app).
- * (This was originally written for 8, based on app/locale/vendor.)
- */
- class ZipSet {
- public:
- ZipSet(void);
- ~ZipSet(void);
-
- /*
- * Return a ZipFileRO structure for a ZipFileRO with the specified
- * parameters.
- */
- ZipFileRO* getZip(const String8& path);
-
- Asset* getZipResourceTableAsset(const String8& path);
- Asset* setZipResourceTableAsset(const String8& path, Asset* asset);
-
- ResTable* getZipResourceTable(const String8& path);
- ResTable* setZipResourceTable(const String8& path, ResTable* res);
-
- // generate path, e.g. "common/en-US-noogle.zip"
- static String8 getPathName(const char* path);
-
- bool isUpToDate();
-
- private:
- void closeZip(int idx);
-
- int getIndex(const String8& zip) const;
- mutable Vector<String8> mZipPath;
- mutable Vector<sp<SharedZip> > mZipFile;
- };
-
- // Protect all internal state.
- mutable Mutex mLock;
-
- ZipSet mZipSet;
-
- Vector<asset_path> mAssetPaths;
- char* mLocale;
- char* mVendor;
-
- mutable ResTable* mResources;
- ResTable_config* mConfig;
-
- /*
- * Cached data for "loose" files. This lets us avoid poking at the
- * filesystem when searching for loose assets. Each entry is the
- * "extended partial" path, e.g. "default/default/foo/bar.txt". The
- * full set of files is present, including ".EXCLUDE" entries.
- *
- * We do not cache directory names. We don't retain the ".gz",
- * because to our clients "foo" and "foo.gz" both look like "foo".
- */
- CacheMode mCacheMode; // is the cache enabled?
- bool mCacheValid; // clear when locale or vendor changes
- SortedVector<AssetDir::FileInfo> mCache;
-};
-
-}; // namespace android
-
-#endif // __LIBS_ASSETMANAGER_H
diff --git a/include/utils/BackupHelpers.h b/include/utils/BackupHelpers.h
deleted file mode 100644
index 1bb04a7..0000000
--- a/include/utils/BackupHelpers.h
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UTILS_BACKUP_HELPERS_H
-#define _UTILS_BACKUP_HELPERS_H
-
-#include <utils/Errors.h>
-#include <utils/String8.h>
-#include <utils/KeyedVector.h>
-
-namespace android {
-
-enum {
- BACKUP_HEADER_ENTITY_V1 = 0x61746144, // Data (little endian)
-};
-
-typedef struct {
- int type; // BACKUP_HEADER_ENTITY_V1
- int keyLen; // length of the key name, not including the null terminator
- int dataSize; // size of the data, not including the padding, -1 means delete
-} entity_header_v1;
-
-struct SnapshotHeader {
- int magic0;
- int fileCount;
- int magic1;
- int totalSize;
-};
-
-struct FileState {
- int modTime_sec;
- int modTime_nsec;
- int mode;
- int size;
- int crc32;
- int nameLen;
-};
-
-struct FileRec {
- String8 file;
- bool deleted;
- FileState s;
-};
-
-
-/**
- * Writes the data.
- *
- * If an error occurs, it poisons this object and all write calls will fail
- * with the error that occurred.
- */
-class BackupDataWriter
-{
-public:
- BackupDataWriter(int fd);
- // does not close fd
- ~BackupDataWriter();
-
- status_t WriteEntityHeader(const String8& key, size_t dataSize);
-
- /* Note: WriteEntityData will write arbitrary data into the file without
- * validation or a previously-supplied header. The full backup implementation
- * uses it this way to generate a controlled binary stream that is not
- * entity-structured. If the implementation here is changed, either this
- * use case must remain valid, or the full backup implementation should be
- * adjusted to use some other appropriate mechanism.
- */
- status_t WriteEntityData(const void* data, size_t size);
-
- void SetKeyPrefix(const String8& keyPrefix);
-
-private:
- explicit BackupDataWriter();
- status_t write_padding_for(int n);
-
- int m_fd;
- status_t m_status;
- ssize_t m_pos;
- int m_entityCount;
- String8 m_keyPrefix;
-};
-
-/**
- * Reads the data.
- *
- * If an error occurs, it poisons this object and all write calls will fail
- * with the error that occurred.
- */
-class BackupDataReader
-{
-public:
- BackupDataReader(int fd);
- // does not close fd
- ~BackupDataReader();
-
- status_t Status();
- status_t ReadNextHeader(bool* done, int* type);
-
- bool HasEntities();
- status_t ReadEntityHeader(String8* key, size_t* dataSize);
- status_t SkipEntityData(); // must be called with the pointer at the beginning of the data.
- ssize_t ReadEntityData(void* data, size_t size);
-
-private:
- explicit BackupDataReader();
- status_t skip_padding();
-
- int m_fd;
- bool m_done;
- status_t m_status;
- ssize_t m_pos;
- ssize_t m_dataEndPos;
- int m_entityCount;
- union {
- int type;
- entity_header_v1 entity;
- } m_header;
- String8 m_key;
-};
-
-int back_up_files(int oldSnapshotFD, BackupDataWriter* dataStream, int newSnapshotFD,
- char const* const* files, char const* const *keys, int fileCount);
-
-int write_tarfile(const String8& packageName, const String8& domain,
- const String8& rootPath, const String8& filePath, BackupDataWriter* outputStream);
-
-class RestoreHelperBase
-{
-public:
- RestoreHelperBase();
- ~RestoreHelperBase();
-
- status_t WriteFile(const String8& filename, BackupDataReader* in);
- status_t WriteSnapshot(int fd);
-
-private:
- void* m_buf;
- bool m_loggedUnknownMetadata;
- KeyedVector<String8,FileRec> m_files;
-};
-
-#define TEST_BACKUP_HELPERS 1
-
-#if TEST_BACKUP_HELPERS
-int backup_helper_test_empty();
-int backup_helper_test_four();
-int backup_helper_test_files();
-int backup_helper_test_null_base();
-int backup_helper_test_missing_file();
-int backup_helper_test_data_writer();
-int backup_helper_test_data_reader();
-#endif
-
-} // namespace android
-
-#endif // _UTILS_BACKUP_HELPERS_H
diff --git a/include/utils/BasicHashtable.h b/include/utils/BasicHashtable.h
new file mode 100644
index 0000000..fdf9738
--- /dev/null
+++ b/include/utils/BasicHashtable.h
@@ -0,0 +1,393 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_BASIC_HASHTABLE_H
+#define ANDROID_BASIC_HASHTABLE_H
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <utils/SharedBuffer.h>
+#include <utils/TypeHelpers.h>
+
+namespace android {
+
+/* Implementation type. Nothing to see here. */
+class BasicHashtableImpl {
+protected:
+ struct Bucket {
+ // The collision flag indicates that the bucket is part of a collision chain
+ // such that at least two entries both hash to this bucket. When true, we
+ // may need to seek further along the chain to find the entry.
+ static const uint32_t COLLISION = 0x80000000UL;
+
+ // The present flag indicates that the bucket contains an initialized entry value.
+ static const uint32_t PRESENT = 0x40000000UL;
+
+ // Mask for 30 bits worth of the hash code that are stored within the bucket to
+ // speed up lookups and rehashing by eliminating the need to recalculate the
+ // hash code of the entry's key.
+ static const uint32_t HASH_MASK = 0x3fffffffUL;
+
+ // Combined value that stores the collision and present flags as well as
+ // a 30 bit hash code.
+ uint32_t cookie;
+
+ // Storage for the entry begins here.
+ char entry[0];
+ };
+
+ BasicHashtableImpl(size_t entrySize, bool hasTrivialDestructor,
+ size_t minimumInitialCapacity, float loadFactor);
+ BasicHashtableImpl(const BasicHashtableImpl& other);
+
+ void dispose();
+
+ inline void edit() {
+ if (mBuckets && !SharedBuffer::bufferFromData(mBuckets)->onlyOwner()) {
+ clone();
+ }
+ }
+
+ void setTo(const BasicHashtableImpl& other);
+ void clear();
+
+ ssize_t next(ssize_t index) const;
+ ssize_t find(ssize_t index, hash_t hash, const void* __restrict__ key) const;
+ size_t add(hash_t hash, const void* __restrict__ entry);
+ void removeAt(size_t index);
+ void rehash(size_t minimumCapacity, float loadFactor);
+
+ const size_t mBucketSize; // number of bytes per bucket including the entry
+ const bool mHasTrivialDestructor; // true if the entry type does not require destruction
+ size_t mCapacity; // number of buckets that can be filled before exceeding load factor
+ float mLoadFactor; // load factor
+ size_t mSize; // number of elements actually in the table
+ size_t mFilledBuckets; // number of buckets for which collision or present is true
+ size_t mBucketCount; // number of slots in the mBuckets array
+ void* mBuckets; // array of buckets, as a SharedBuffer
+
+ inline const Bucket& bucketAt(const void* __restrict__ buckets, size_t index) const {
+ return *reinterpret_cast<const Bucket*>(
+ static_cast<const uint8_t*>(buckets) + index * mBucketSize);
+ }
+
+ inline Bucket& bucketAt(void* __restrict__ buckets, size_t index) const {
+ return *reinterpret_cast<Bucket*>(static_cast<uint8_t*>(buckets) + index * mBucketSize);
+ }
+
+ virtual bool compareBucketKey(const Bucket& bucket, const void* __restrict__ key) const = 0;
+ virtual void initializeBucketEntry(Bucket& bucket, const void* __restrict__ entry) const = 0;
+ virtual void destroyBucketEntry(Bucket& bucket) const = 0;
+
+private:
+ void clone();
+
+ // Allocates a bucket array as a SharedBuffer.
+ void* allocateBuckets(size_t count) const;
+
+ // Releases a bucket array's associated SharedBuffer.
+ void releaseBuckets(void* __restrict__ buckets, size_t count) const;
+
+ // Destroys the contents of buckets (invokes destroyBucketEntry for each
+ // populated bucket if needed).
+ void destroyBuckets(void* __restrict__ buckets, size_t count) const;
+
+ // Copies the content of buckets (copies the cookie and invokes copyBucketEntry
+ // for each populated bucket if needed).
+ void copyBuckets(const void* __restrict__ fromBuckets,
+ void* __restrict__ toBuckets, size_t count) const;
+
+ // Determines the appropriate size of a bucket array to store a certain minimum
+ // number of entries and returns its effective capacity.
+ static void determineCapacity(size_t minimumCapacity, float loadFactor,
+ size_t* __restrict__ outBucketCount, size_t* __restrict__ outCapacity);
+
+ // Trim a hash code to 30 bits to match what we store in the bucket's cookie.
+ inline static hash_t trimHash(hash_t hash) {
+ return (hash & Bucket::HASH_MASK) ^ (hash >> 30);
+ }
+
+ // Returns the index of the first bucket that is in the collision chain
+ // for the specified hash code, given the total number of buckets.
+ // (Primary hash)
+ inline static size_t chainStart(hash_t hash, size_t count) {
+ return hash % count;
+ }
+
+ // Returns the increment to add to a bucket index to seek to the next bucket
+ // in the collision chain for the specified hash code, given the total number of buckets.
+ // (Secondary hash)
+ inline static size_t chainIncrement(hash_t hash, size_t count) {
+ return ((hash >> 7) | (hash << 25)) % (count - 1) + 1;
+ }
+
+ // Returns the index of the next bucket that is in the collision chain
+ // that is defined by the specified increment, given the total number of buckets.
+ inline static size_t chainSeek(size_t index, size_t increment, size_t count) {
+ return (index + increment) % count;
+ }
+};
+
+/*
+ * A BasicHashtable stores entries that are indexed by hash code in place
+ * within an array. The basic operations are finding entries by key,
+ * adding new entries and removing existing entries.
+ *
+ * This class provides a very limited set of operations with simple semantics.
+ * It is intended to be used as a building block to construct more complex
+ * and interesting data structures such as HashMap. Think very hard before
+ * adding anything extra to BasicHashtable, it probably belongs at a
+ * higher level of abstraction.
+ *
+ * TKey: The key type.
+ * TEntry: The entry type which is what is actually stored in the array.
+ *
+ * TKey must support the following contract:
+ * bool operator==(const TKey& other) const; // return true if equal
+ * bool operator!=(const TKey& other) const; // return true if unequal
+ *
+ * TEntry must support the following contract:
+ * const TKey& getKey() const; // get the key from the entry
+ *
+ * This class supports storing entries with duplicate keys. Of course, it can't
+ * tell them apart during removal so only the first entry will be removed.
+ * We do this because it means that operations like add() can't fail.
+ */
+template <typename TKey, typename TEntry>
+class BasicHashtable : private BasicHashtableImpl {
+public:
+ /* Creates a hashtable with the specified minimum initial capacity.
+ * The underlying array will be created when the first entry is added.
+ *
+ * minimumInitialCapacity: The minimum initial capacity for the hashtable.
+ * Default is 0.
+ * loadFactor: The desired load factor for the hashtable, between 0 and 1.
+ * Default is 0.75.
+ */
+ BasicHashtable(size_t minimumInitialCapacity = 0, float loadFactor = 0.75f);
+
+ /* Copies a hashtable.
+ * The underlying storage is shared copy-on-write.
+ */
+ BasicHashtable(const BasicHashtable& other);
+
+ /* Clears and destroys the hashtable.
+ */
+ virtual ~BasicHashtable();
+
+ /* Making this hashtable a copy of the other hashtable.
+ * The underlying storage is shared copy-on-write.
+ *
+ * other: The hashtable to copy.
+ */
+ inline BasicHashtable<TKey, TEntry>& operator =(const BasicHashtable<TKey, TEntry> & other) {
+ setTo(other);
+ return *this;
+ }
+
+ /* Returns the number of entries in the hashtable.
+ */
+ inline size_t size() const {
+ return mSize;
+ }
+
+ /* Returns the capacity of the hashtable, which is the number of elements that can
+ * added to the hashtable without requiring it to be grown.
+ */
+ inline size_t capacity() const {
+ return mCapacity;
+ }
+
+ /* Returns the number of buckets that the hashtable has, which is the size of its
+ * underlying array.
+ */
+ inline size_t bucketCount() const {
+ return mBucketCount;
+ }
+
+ /* Returns the load factor of the hashtable. */
+ inline float loadFactor() const {
+ return mLoadFactor;
+ };
+
+ /* Returns a const reference to the entry at the specified index.
+ *
+ * index: The index of the entry to retrieve. Must be a valid index within
+ * the bounds of the hashtable.
+ */
+ inline const TEntry& entryAt(size_t index) const {
+ return entryFor(bucketAt(mBuckets, index));
+ }
+
+ /* Returns a non-const reference to the entry at the specified index.
+ *
+ * index: The index of the entry to edit. Must be a valid index within
+ * the bounds of the hashtable.
+ */
+ inline TEntry& editEntryAt(size_t index) {
+ edit();
+ return entryFor(bucketAt(mBuckets, index));
+ }
+
+ /* Clears the hashtable.
+ * All entries in the hashtable are destroyed immediately.
+ * If you need to do something special with the entries in the hashtable then iterate
+ * over them and do what you need before clearing the hashtable.
+ */
+ inline void clear() {
+ BasicHashtableImpl::clear();
+ }
+
+ /* Returns the index of the next entry in the hashtable given the index of a previous entry.
+ * If the given index is -1, then returns the index of the first entry in the hashtable,
+ * if there is one, or -1 otherwise.
+ * If the given index is not -1, then returns the index of the next entry in the hashtable,
+ * in strictly increasing order, or -1 if there are none left.
+ *
+ * index: The index of the previous entry that was iterated, or -1 to begin
+ * iteration at the beginning of the hashtable.
+ */
+ inline ssize_t next(ssize_t index) const {
+ return BasicHashtableImpl::next(index);
+ }
+
+ /* Finds the index of an entry with the specified key.
+ * If the given index is -1, then returns the index of the first matching entry,
+ * otherwise returns the index of the next matching entry.
+ * If the hashtable contains multiple entries with keys that match the requested
+ * key, then the sequence of entries returned is arbitrary.
+ * Returns -1 if no entry was found.
+ *
+ * index: The index of the previous entry with the specified key, or -1 to
+ * find the first matching entry.
+ * hash: The hashcode of the key.
+ * key: The key.
+ */
+ inline ssize_t find(ssize_t index, hash_t hash, const TKey& key) const {
+ return BasicHashtableImpl::find(index, hash, &key);
+ }
+
+ /* Adds the entry to the hashtable.
+ * Returns the index of the newly added entry.
+ * If an entry with the same key already exists, then a duplicate entry is added.
+ * If the entry will not fit, then the hashtable's capacity is increased and
+ * its contents are rehashed. See rehash().
+ *
+ * hash: The hashcode of the key.
+ * entry: The entry to add.
+ */
+ inline size_t add(hash_t hash, const TEntry& entry) {
+ return BasicHashtableImpl::add(hash, &entry);
+ }
+
+ /* Removes the entry with the specified index from the hashtable.
+ * The entry is destroyed immediately.
+ * The index must be valid.
+ *
+ * The hashtable is not compacted after an item is removed, so it is legal
+ * to continue iterating over the hashtable using next() or find().
+ *
+ * index: The index of the entry to remove. Must be a valid index within the
+ * bounds of the hashtable, and it must refer to an existing entry.
+ */
+ inline void removeAt(size_t index) {
+ BasicHashtableImpl::removeAt(index);
+ }
+
+ /* Rehashes the contents of the hashtable.
+ * Grows the hashtable to at least the specified minimum capacity or the
+ * current number of elements, whichever is larger.
+ *
+ * Rehashing causes all entries to be copied and the entry indices may change.
+ * Although the hash codes are cached by the hashtable, rehashing can be an
+ * expensive operation and should be avoided unless the hashtable's size
+ * needs to be changed.
+ *
+ * Rehashing is the only way to change the capacity or load factor of the
+ * hashtable once it has been created. It can be used to compact the
+ * hashtable by choosing a minimum capacity that is smaller than the current
+ * capacity (such as 0).
+ *
+ * minimumCapacity: The desired minimum capacity after rehashing.
+ * loadFactor: The desired load factor after rehashing.
+ */
+ inline void rehash(size_t minimumCapacity, float loadFactor) {
+ BasicHashtableImpl::rehash(minimumCapacity, loadFactor);
+ }
+
+protected:
+ static inline const TEntry& entryFor(const Bucket& bucket) {
+ return reinterpret_cast<const TEntry&>(bucket.entry);
+ }
+
+ static inline TEntry& entryFor(Bucket& bucket) {
+ return reinterpret_cast<TEntry&>(bucket.entry);
+ }
+
+ virtual bool compareBucketKey(const Bucket& bucket, const void* __restrict__ key) const;
+ virtual void initializeBucketEntry(Bucket& bucket, const void* __restrict__ entry) const;
+ virtual void destroyBucketEntry(Bucket& bucket) const;
+
+private:
+ // For dumping the raw contents of a hashtable during testing.
+ friend class BasicHashtableTest;
+ inline uint32_t cookieAt(size_t index) const {
+ return bucketAt(mBuckets, index).cookie;
+ }
+};
+
+template <typename TKey, typename TEntry>
+BasicHashtable<TKey, TEntry>::BasicHashtable(size_t minimumInitialCapacity, float loadFactor) :
+ BasicHashtableImpl(sizeof(TEntry), traits<TEntry>::has_trivial_dtor,
+ minimumInitialCapacity, loadFactor) {
+}
+
+template <typename TKey, typename TEntry>
+BasicHashtable<TKey, TEntry>::BasicHashtable(const BasicHashtable<TKey, TEntry>& other) :
+ BasicHashtableImpl(other) {
+}
+
+template <typename TKey, typename TEntry>
+BasicHashtable<TKey, TEntry>::~BasicHashtable() {
+ dispose();
+}
+
+template <typename TKey, typename TEntry>
+bool BasicHashtable<TKey, TEntry>::compareBucketKey(const Bucket& bucket,
+ const void* __restrict__ key) const {
+ return entryFor(bucket).getKey() == *static_cast<const TKey*>(key);
+}
+
+template <typename TKey, typename TEntry>
+void BasicHashtable<TKey, TEntry>::initializeBucketEntry(Bucket& bucket,
+ const void* __restrict__ entry) const {
+ if (!traits<TEntry>::has_trivial_copy) {
+ new (&entryFor(bucket)) TEntry(*(static_cast<const TEntry*>(entry)));
+ } else {
+ memcpy(&entryFor(bucket), entry, sizeof(TEntry));
+ }
+}
+
+template <typename TKey, typename TEntry>
+void BasicHashtable<TKey, TEntry>::destroyBucketEntry(Bucket& bucket) const {
+ if (!traits<TEntry>::has_trivial_dtor) {
+ entryFor(bucket).~TEntry();
+ }
+}
+
+}; // namespace android
+
+#endif // ANDROID_BASIC_HASHTABLE_H
diff --git a/include/utils/CallStack.h b/include/utils/CallStack.h
index 8817120..079e20c 100644
--- a/include/utils/CallStack.h
+++ b/include/utils/CallStack.h
@@ -21,6 +21,7 @@
#include <sys/types.h>
#include <utils/String8.h>
+#include <corkscrew/backtrace.h>
// ---------------------------------------------------------------------------
@@ -61,11 +62,8 @@ public:
size_t size() const { return mCount; }
private:
- // Internal helper function
- String8 toStringSingleLevel(const char* prefix, int32_t level) const;
-
- size_t mCount;
- const void* mStack[MAX_DEPTH];
+ size_t mCount;
+ backtrace_frame_t mStack[MAX_DEPTH];
};
}; // namespace android
diff --git a/include/utils/GenerationCache.h b/include/utils/GenerationCache.h
index bb9ddd6..40722d1 100644
--- a/include/utils/GenerationCache.h
+++ b/include/utils/GenerationCache.h
@@ -34,17 +34,17 @@ public:
template<typename EntryKey, typename EntryValue>
struct Entry: public LightRefBase<Entry<EntryKey, EntryValue> > {
- Entry() { }
- Entry(const Entry<EntryKey, EntryValue>& e):
- key(e.key), value(e.value), parent(e.parent), child(e.child) { }
- Entry(sp<Entry<EntryKey, EntryValue> > e):
- key(e->key), value(e->value), parent(e->parent), child(e->child) { }
+ Entry(const Entry<EntryKey, EntryValue>& e) :
+ key(e.key), value(e.value),
+ parent(e.parent), child(e.child) { }
+ Entry(const EntryKey& key, const EntryValue& value) :
+ key(key), value(value) { }
EntryKey key;
EntryValue value;
- sp<Entry<EntryKey, EntryValue> > parent;
- sp<Entry<EntryKey, EntryValue> > child;
+ sp<Entry<EntryKey, EntryValue> > parent; // next older entry
+ sp<Entry<EntryKey, EntryValue> > child; // next younger entry
}; // struct Entry
/**
@@ -62,23 +62,20 @@ public:
void setOnEntryRemovedListener(OnEntryRemoved<K, V>* listener);
- void clear();
+ size_t size() const;
- bool contains(K key) const;
- V get(K key);
- K getKeyAt(uint32_t index) const;
- bool put(K key, V value);
- V remove(K key);
- V removeOldest();
- V getValueAt(uint32_t index) const;
+ void clear();
- uint32_t size() const;
+ bool contains(const K& key) const;
+ const K& getKeyAt(size_t index) const;
+ const V& getValueAt(size_t index) const;
- void addToCache(sp<Entry<K, V> > entry, K key, V value);
- void attachToCache(sp<Entry<K, V> > entry);
- void detachFromCache(sp<Entry<K, V> > entry);
+ const V& get(const K& key);
+ bool put(const K& key, const V& value);
- V removeAt(ssize_t index);
+ void removeAt(ssize_t index);
+ bool remove(const K& key);
+ bool removeOldest();
private:
KeyedVector<K, sp<Entry<K, V> > > mCache;
@@ -88,11 +85,16 @@ private:
sp<Entry<K, V> > mOldest;
sp<Entry<K, V> > mYoungest;
+
+ void attachToCache(const sp<Entry<K, V> >& entry);
+ void detachFromCache(const sp<Entry<K, V> >& entry);
+
+ const V mNullValue;
}; // class GenerationCache
template<typename K, typename V>
GenerationCache<K, V>::GenerationCache(uint32_t maxCapacity): mMaxCapacity(maxCapacity),
- mListener(NULL) {
+ mListener(NULL), mNullValue(NULL) {
};
template<typename K, typename V>
@@ -130,45 +132,44 @@ void GenerationCache<K, V>::clear() {
}
template<typename K, typename V>
-bool GenerationCache<K, V>::contains(K key) const {
+bool GenerationCache<K, V>::contains(const K& key) const {
return mCache.indexOfKey(key) >= 0;
}
template<typename K, typename V>
-K GenerationCache<K, V>::getKeyAt(uint32_t index) const {
+const K& GenerationCache<K, V>::getKeyAt(size_t index) const {
return mCache.keyAt(index);
}
template<typename K, typename V>
-V GenerationCache<K, V>::getValueAt(uint32_t index) const {
+const V& GenerationCache<K, V>::getValueAt(size_t index) const {
return mCache.valueAt(index)->value;
}
template<typename K, typename V>
-V GenerationCache<K, V>::get(K key) {
+const V& GenerationCache<K, V>::get(const K& key) {
ssize_t index = mCache.indexOfKey(key);
if (index >= 0) {
- sp<Entry<K, V> > entry = mCache.valueAt(index);
- if (entry.get()) {
- detachFromCache(entry);
- attachToCache(entry);
- return entry->value;
- }
+ const sp<Entry<K, V> >& entry = mCache.valueAt(index);
+ detachFromCache(entry);
+ attachToCache(entry);
+ return entry->value;
}
- return NULL;
+ return mNullValue;
}
template<typename K, typename V>
-bool GenerationCache<K, V>::put(K key, V value) {
+bool GenerationCache<K, V>::put(const K& key, const V& value) {
if (mMaxCapacity != kUnlimitedCapacity && mCache.size() >= mMaxCapacity) {
removeOldest();
}
ssize_t index = mCache.indexOfKey(key);
if (index < 0) {
- sp<Entry<K, V> > entry = new Entry<K, V>;
- addToCache(entry, key, value);
+ sp<Entry<K, V> > entry = new Entry<K, V>(key, value);
+ mCache.add(key, entry);
+ attachToCache(entry);
return true;
}
@@ -176,49 +177,44 @@ bool GenerationCache<K, V>::put(K key, V value) {
}
template<typename K, typename V>
-void GenerationCache<K, V>::addToCache(sp<Entry<K, V> > entry, K key, V value) {
- entry->key = key;
- entry->value = value;
- mCache.add(key, entry);
- attachToCache(entry);
-}
-
-template<typename K, typename V>
-V GenerationCache<K, V>::remove(K key) {
+bool GenerationCache<K, V>::remove(const K& key) {
ssize_t index = mCache.indexOfKey(key);
if (index >= 0) {
- return removeAt(index);
+ removeAt(index);
+ return true;
}
- return NULL;
+ return false;
}
template<typename K, typename V>
-V GenerationCache<K, V>::removeAt(ssize_t index) {
+void GenerationCache<K, V>::removeAt(ssize_t index) {
sp<Entry<K, V> > entry = mCache.valueAt(index);
if (mListener) {
(*mListener)(entry->key, entry->value);
}
mCache.removeItemsAt(index, 1);
detachFromCache(entry);
-
- return entry->value;
}
template<typename K, typename V>
-V GenerationCache<K, V>::removeOldest() {
+bool GenerationCache<K, V>::removeOldest() {
if (mOldest.get()) {
ssize_t index = mCache.indexOfKey(mOldest->key);
if (index >= 0) {
- return removeAt(index);
+ removeAt(index);
+ return true;
}
+ ALOGE("GenerationCache: removeOldest failed to find the item in the cache "
+ "with the given key, but we know it must be in there. "
+ "Is the key comparator kaput?");
}
- return NULL;
+ return false;
}
template<typename K, typename V>
-void GenerationCache<K, V>::attachToCache(sp<Entry<K, V> > entry) {
+void GenerationCache<K, V>::attachToCache(const sp<Entry<K, V> >& entry) {
if (!mYoungest.get()) {
mYoungest = mOldest = entry;
} else {
@@ -229,20 +225,16 @@ void GenerationCache<K, V>::attachToCache(sp<Entry<K, V> > entry) {
}
template<typename K, typename V>
-void GenerationCache<K, V>::detachFromCache(sp<Entry<K, V> > entry) {
+void GenerationCache<K, V>::detachFromCache(const sp<Entry<K, V> >& entry) {
if (entry->parent.get()) {
entry->parent->child = entry->child;
+ } else {
+ mOldest = entry->child;
}
if (entry->child.get()) {
entry->child->parent = entry->parent;
- }
-
- if (mOldest == entry) {
- mOldest = entry->child;
- }
-
- if (mYoungest == entry) {
+ } else {
mYoungest = entry->parent;
}
diff --git a/include/utils/KeyedVector.h b/include/utils/KeyedVector.h
index 65165a2..85535bd 100644
--- a/include/utils/KeyedVector.h
+++ b/include/utils/KeyedVector.h
@@ -66,7 +66,7 @@ public:
ssize_t indexOfKey(const KEY& key) const;
/*!
- * modifing the array
+ * modifying the array
*/
VALUE& editValueFor(const KEY& key);
diff --git a/include/utils/ObbFile.h b/include/utils/ObbFile.h
deleted file mode 100644
index 47559cd..0000000
--- a/include/utils/ObbFile.h
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef OBBFILE_H_
-#define OBBFILE_H_
-
-#include <stdint.h>
-#include <strings.h>
-
-#include <utils/RefBase.h>
-#include <utils/String8.h>
-
-namespace android {
-
-// OBB flags (bit 0)
-#define OBB_OVERLAY (1 << 0)
-#define OBB_SALTED (1 << 1)
-
-class ObbFile : public RefBase {
-protected:
- virtual ~ObbFile();
-
-public:
- ObbFile();
-
- bool readFrom(const char* filename);
- bool readFrom(int fd);
- bool writeTo(const char* filename);
- bool writeTo(int fd);
- bool removeFrom(const char* filename);
- bool removeFrom(int fd);
-
- const char* getFileName() const {
- return mFileName;
- }
-
- const String8 getPackageName() const {
- return mPackageName;
- }
-
- void setPackageName(String8 packageName) {
- mPackageName = packageName;
- }
-
- int32_t getVersion() const {
- return mVersion;
- }
-
- void setVersion(int32_t version) {
- mVersion = version;
- }
-
- int32_t getFlags() const {
- return mFlags;
- }
-
- void setFlags(int32_t flags) {
- mFlags = flags;
- }
-
- const unsigned char* getSalt(size_t* length) const {
- if ((mFlags & OBB_SALTED) == 0) {
- *length = 0;
- return NULL;
- }
-
- *length = sizeof(mSalt);
- return mSalt;
- }
-
- bool setSalt(const unsigned char* salt, size_t length) {
- if (length != sizeof(mSalt)) {
- return false;
- }
-
- memcpy(mSalt, salt, sizeof(mSalt));
- mFlags |= OBB_SALTED;
- return true;
- }
-
- bool isOverlay() {
- return (mFlags & OBB_OVERLAY) == OBB_OVERLAY;
- }
-
- void setOverlay(bool overlay) {
- if (overlay) {
- mFlags |= OBB_OVERLAY;
- } else {
- mFlags &= ~OBB_OVERLAY;
- }
- }
-
- static inline uint32_t get4LE(const unsigned char* buf) {
- return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
- }
-
- static inline void put4LE(unsigned char* buf, uint32_t val) {
- buf[0] = val & 0xFF;
- buf[1] = (val >> 8) & 0xFF;
- buf[2] = (val >> 16) & 0xFF;
- buf[3] = (val >> 24) & 0xFF;
- }
-
-private:
- /* Package name this ObbFile is associated with */
- String8 mPackageName;
-
- /* Package version this ObbFile is associated with */
- int32_t mVersion;
-
- /* Flags for this OBB type. */
- int32_t mFlags;
-
- /* Whether the file is salted. */
- bool mSalted;
-
- /* The encryption salt. */
- unsigned char mSalt[8];
-
- const char* mFileName;
-
- size_t mFileSize;
-
- size_t mFooterStart;
-
- unsigned char* mReadBuf;
-
- bool parseObbFile(int fd);
-};
-
-}
-#endif /* OBBFILE_H_ */
diff --git a/include/utils/ResourceTypes.h b/include/utils/ResourceTypes.h
deleted file mode 100644
index 71e5324..0000000
--- a/include/utils/ResourceTypes.h
+++ /dev/null
@@ -1,2128 +0,0 @@
-/*
- * Copyright (C) 2005 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//
-// Definitions of resource data structures.
-//
-#ifndef _LIBS_UTILS_RESOURCE_TYPES_H
-#define _LIBS_UTILS_RESOURCE_TYPES_H
-
-#include <utils/Asset.h>
-#include <utils/ByteOrder.h>
-#include <utils/Errors.h>
-#include <utils/String16.h>
-#include <utils/Vector.h>
-
-#include <utils/threads.h>
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <android/configuration.h>
-
-namespace android {
-
-/** ********************************************************************
- * PNG Extensions
- *
- * New private chunks that may be placed in PNG images.
- *
- *********************************************************************** */
-
-/**
- * This chunk specifies how to split an image into segments for
- * scaling.
- *
- * There are J horizontal and K vertical segments. These segments divide
- * the image into J*K regions as follows (where J=4 and K=3):
- *
- * F0 S0 F1 S1
- * +-----+----+------+-------+
- * S2| 0 | 1 | 2 | 3 |
- * +-----+----+------+-------+
- * | | | | |
- * | | | | |
- * F2| 4 | 5 | 6 | 7 |
- * | | | | |
- * | | | | |
- * +-----+----+------+-------+
- * S3| 8 | 9 | 10 | 11 |
- * +-----+----+------+-------+
- *
- * Each horizontal and vertical segment is considered to by either
- * stretchable (marked by the Sx labels) or fixed (marked by the Fy
- * labels), in the horizontal or vertical axis, respectively. In the
- * above example, the first is horizontal segment (F0) is fixed, the
- * next is stretchable and then they continue to alternate. Note that
- * the segment list for each axis can begin or end with a stretchable
- * or fixed segment.
- *
- * The relative sizes of the stretchy segments indicates the relative
- * amount of stretchiness of the regions bordered by the segments. For
- * example, regions 3, 7 and 11 above will take up more horizontal space
- * than regions 1, 5 and 9 since the horizontal segment associated with
- * the first set of regions is larger than the other set of regions. The
- * ratios of the amount of horizontal (or vertical) space taken by any
- * two stretchable slices is exactly the ratio of their corresponding
- * segment lengths.
- *
- * xDivs and yDivs point to arrays of horizontal and vertical pixel
- * indices. The first pair of Divs (in either array) indicate the
- * starting and ending points of the first stretchable segment in that
- * axis. The next pair specifies the next stretchable segment, etc. So
- * in the above example xDiv[0] and xDiv[1] specify the horizontal
- * coordinates for the regions labeled 1, 5 and 9. xDiv[2] and
- * xDiv[3] specify the coordinates for regions 3, 7 and 11. Note that
- * the leftmost slices always start at x=0 and the rightmost slices
- * always end at the end of the image. So, for example, the regions 0,
- * 4 and 8 (which are fixed along the X axis) start at x value 0 and
- * go to xDiv[0] and slices 2, 6 and 10 start at xDiv[1] and end at
- * xDiv[2].
- *
- * The array pointed to by the colors field lists contains hints for
- * each of the regions. They are ordered according left-to-right and
- * top-to-bottom as indicated above. For each segment that is a solid
- * color the array entry will contain that color value; otherwise it
- * will contain NO_COLOR. Segments that are completely transparent
- * will always have the value TRANSPARENT_COLOR.
- *
- * The PNG chunk type is "npTc".
- */
-struct Res_png_9patch
-{
- Res_png_9patch() : wasDeserialized(false), xDivs(NULL),
- yDivs(NULL), colors(NULL) { }
-
- int8_t wasDeserialized;
- int8_t numXDivs;
- int8_t numYDivs;
- int8_t numColors;
-
- // These tell where the next section of a patch starts.
- // For example, the first patch includes the pixels from
- // 0 to xDivs[0]-1 and the second patch includes the pixels
- // from xDivs[0] to xDivs[1]-1.
- // Note: allocation/free of these pointers is left to the caller.
- int32_t* xDivs;
- int32_t* yDivs;
-
- int32_t paddingLeft, paddingRight;
- int32_t paddingTop, paddingBottom;
-
- enum {
- // The 9 patch segment is not a solid color.
- NO_COLOR = 0x00000001,
-
- // The 9 patch segment is completely transparent.
- TRANSPARENT_COLOR = 0x00000000
- };
- // Note: allocation/free of this pointer is left to the caller.
- uint32_t* colors;
-
- // Convert data from device representation to PNG file representation.
- void deviceToFile();
- // Convert data from PNG file representation to device representation.
- void fileToDevice();
- // Serialize/Marshall the patch data into a newly malloc-ed block
- void* serialize();
- // Serialize/Marshall the patch data
- void serialize(void* outData);
- // Deserialize/Unmarshall the patch data
- static Res_png_9patch* deserialize(const void* data);
- // Compute the size of the serialized data structure
- size_t serializedSize();
-};
-
-/** ********************************************************************
- * Base Types
- *
- * These are standard types that are shared between multiple specific
- * resource types.
- *
- *********************************************************************** */
-
-/**
- * Header that appears at the front of every data chunk in a resource.
- */
-struct ResChunk_header
-{
- // Type identifier for this chunk. The meaning of this value depends
- // on the containing chunk.
- uint16_t type;
-
- // Size of the chunk header (in bytes). Adding this value to
- // the address of the chunk allows you to find its associated data
- // (if any).
- uint16_t headerSize;
-
- // Total size of this chunk (in bytes). This is the chunkSize plus
- // the size of any data associated with the chunk. Adding this value
- // to the chunk allows you to completely skip its contents (including
- // any child chunks). If this value is the same as chunkSize, there is
- // no data associated with the chunk.
- uint32_t size;
-};
-
-enum {
- RES_NULL_TYPE = 0x0000,
- RES_STRING_POOL_TYPE = 0x0001,
- RES_TABLE_TYPE = 0x0002,
- RES_XML_TYPE = 0x0003,
-
- // Chunk types in RES_XML_TYPE
- RES_XML_FIRST_CHUNK_TYPE = 0x0100,
- RES_XML_START_NAMESPACE_TYPE= 0x0100,
- RES_XML_END_NAMESPACE_TYPE = 0x0101,
- RES_XML_START_ELEMENT_TYPE = 0x0102,
- RES_XML_END_ELEMENT_TYPE = 0x0103,
- RES_XML_CDATA_TYPE = 0x0104,
- RES_XML_LAST_CHUNK_TYPE = 0x017f,
- // This contains a uint32_t array mapping strings in the string
- // pool back to resource identifiers. It is optional.
- RES_XML_RESOURCE_MAP_TYPE = 0x0180,
-
- // Chunk types in RES_TABLE_TYPE
- RES_TABLE_PACKAGE_TYPE = 0x0200,
- RES_TABLE_TYPE_TYPE = 0x0201,
- RES_TABLE_TYPE_SPEC_TYPE = 0x0202
-};
-
-/**
- * Macros for building/splitting resource identifiers.
- */
-#define Res_VALIDID(resid) (resid != 0)
-#define Res_CHECKID(resid) ((resid&0xFFFF0000) != 0)
-#define Res_MAKEID(package, type, entry) \
- (((package+1)<<24) | (((type+1)&0xFF)<<16) | (entry&0xFFFF))
-#define Res_GETPACKAGE(id) ((id>>24)-1)
-#define Res_GETTYPE(id) (((id>>16)&0xFF)-1)
-#define Res_GETENTRY(id) (id&0xFFFF)
-
-#define Res_INTERNALID(resid) ((resid&0xFFFF0000) != 0 && (resid&0xFF0000) == 0)
-#define Res_MAKEINTERNAL(entry) (0x01000000 | (entry&0xFFFF))
-#define Res_MAKEARRAY(entry) (0x02000000 | (entry&0xFFFF))
-
-#define Res_MAXPACKAGE 255
-
-/**
- * Representation of a value in a resource, supplying type
- * information.
- */
-struct Res_value
-{
- // Number of bytes in this structure.
- uint16_t size;
-
- // Always set to 0.
- uint8_t res0;
-
- // Type of the data value.
- enum {
- // Contains no data.
- TYPE_NULL = 0x00,
- // The 'data' holds a ResTable_ref, a reference to another resource
- // table entry.
- TYPE_REFERENCE = 0x01,
- // The 'data' holds an attribute resource identifier.
- TYPE_ATTRIBUTE = 0x02,
- // The 'data' holds an index into the containing resource table's
- // global value string pool.
- TYPE_STRING = 0x03,
- // The 'data' holds a single-precision floating point number.
- TYPE_FLOAT = 0x04,
- // The 'data' holds a complex number encoding a dimension value,
- // such as "100in".
- TYPE_DIMENSION = 0x05,
- // The 'data' holds a complex number encoding a fraction of a
- // container.
- TYPE_FRACTION = 0x06,
-
- // Beginning of integer flavors...
- TYPE_FIRST_INT = 0x10,
-
- // The 'data' is a raw integer value of the form n..n.
- TYPE_INT_DEC = 0x10,
- // The 'data' is a raw integer value of the form 0xn..n.
- TYPE_INT_HEX = 0x11,
- // The 'data' is either 0 or 1, for input "false" or "true" respectively.
- TYPE_INT_BOOLEAN = 0x12,
-
- // Beginning of color integer flavors...
- TYPE_FIRST_COLOR_INT = 0x1c,
-
- // The 'data' is a raw integer value of the form #aarrggbb.
- TYPE_INT_COLOR_ARGB8 = 0x1c,
- // The 'data' is a raw integer value of the form #rrggbb.
- TYPE_INT_COLOR_RGB8 = 0x1d,
- // The 'data' is a raw integer value of the form #argb.
- TYPE_INT_COLOR_ARGB4 = 0x1e,
- // The 'data' is a raw integer value of the form #rgb.
- TYPE_INT_COLOR_RGB4 = 0x1f,
-
- // ...end of integer flavors.
- TYPE_LAST_COLOR_INT = 0x1f,
-
- // ...end of integer flavors.
- TYPE_LAST_INT = 0x1f
- };
- uint8_t dataType;
-
- // Structure of complex data values (TYPE_UNIT and TYPE_FRACTION)
- enum {
- // Where the unit type information is. This gives us 16 possible
- // types, as defined below.
- COMPLEX_UNIT_SHIFT = 0,
- COMPLEX_UNIT_MASK = 0xf,
-
- // TYPE_DIMENSION: Value is raw pixels.
- COMPLEX_UNIT_PX = 0,
- // TYPE_DIMENSION: Value is Device Independent Pixels.
- COMPLEX_UNIT_DIP = 1,
- // TYPE_DIMENSION: Value is a Scaled device independent Pixels.
- COMPLEX_UNIT_SP = 2,
- // TYPE_DIMENSION: Value is in points.
- COMPLEX_UNIT_PT = 3,
- // TYPE_DIMENSION: Value is in inches.
- COMPLEX_UNIT_IN = 4,
- // TYPE_DIMENSION: Value is in millimeters.
- COMPLEX_UNIT_MM = 5,
-
- // TYPE_FRACTION: A basic fraction of the overall size.
- COMPLEX_UNIT_FRACTION = 0,
- // TYPE_FRACTION: A fraction of the parent size.
- COMPLEX_UNIT_FRACTION_PARENT = 1,
-
- // Where the radix information is, telling where the decimal place
- // appears in the mantissa. This give us 4 possible fixed point
- // representations as defined below.
- COMPLEX_RADIX_SHIFT = 4,
- COMPLEX_RADIX_MASK = 0x3,
-
- // The mantissa is an integral number -- i.e., 0xnnnnnn.0
- COMPLEX_RADIX_23p0 = 0,
- // The mantissa magnitude is 16 bits -- i.e, 0xnnnn.nn
- COMPLEX_RADIX_16p7 = 1,
- // The mantissa magnitude is 8 bits -- i.e, 0xnn.nnnn
- COMPLEX_RADIX_8p15 = 2,
- // The mantissa magnitude is 0 bits -- i.e, 0x0.nnnnnn
- COMPLEX_RADIX_0p23 = 3,
-
- // Where the actual value is. This gives us 23 bits of
- // precision. The top bit is the sign.
- COMPLEX_MANTISSA_SHIFT = 8,
- COMPLEX_MANTISSA_MASK = 0xffffff
- };
-
- // The data for this item, as interpreted according to dataType.
- uint32_t data;
-
- void copyFrom_dtoh(const Res_value& src);
-};
-
-/**
- * This is a reference to a unique entry (a ResTable_entry structure)
- * in a resource table. The value is structured as: 0xpptteeee,
- * where pp is the package index, tt is the type index in that
- * package, and eeee is the entry index in that type. The package
- * and type values start at 1 for the first item, to help catch cases
- * where they have not been supplied.
- */
-struct ResTable_ref
-{
- uint32_t ident;
-};
-
-/**
- * Reference to a string in a string pool.
- */
-struct ResStringPool_ref
-{
- // Index into the string pool table (uint32_t-offset from the indices
- // immediately after ResStringPool_header) at which to find the location
- // of the string data in the pool.
- uint32_t index;
-};
-
-/** ********************************************************************
- * String Pool
- *
- * A set of strings that can be references by others through a
- * ResStringPool_ref.
- *
- *********************************************************************** */
-
-/**
- * Definition for a pool of strings. The data of this chunk is an
- * array of uint32_t providing indices into the pool, relative to
- * stringsStart. At stringsStart are all of the UTF-16 strings
- * concatenated together; each starts with a uint16_t of the string's
- * length and each ends with a 0x0000 terminator. If a string is >
- * 32767 characters, the high bit of the length is set meaning to take
- * those 15 bits as a high word and it will be followed by another
- * uint16_t containing the low word.
- *
- * If styleCount is not zero, then immediately following the array of
- * uint32_t indices into the string table is another array of indices
- * into a style table starting at stylesStart. Each entry in the
- * style table is an array of ResStringPool_span structures.
- */
-struct ResStringPool_header
-{
- struct ResChunk_header header;
-
- // Number of strings in this pool (number of uint32_t indices that follow
- // in the data).
- uint32_t stringCount;
-
- // Number of style span arrays in the pool (number of uint32_t indices
- // follow the string indices).
- uint32_t styleCount;
-
- // Flags.
- enum {
- // If set, the string index is sorted by the string values (based
- // on strcmp16()).
- SORTED_FLAG = 1<<0,
-
- // String pool is encoded in UTF-8
- UTF8_FLAG = 1<<8
- };
- uint32_t flags;
-
- // Index from header of the string data.
- uint32_t stringsStart;
-
- // Index from header of the style data.
- uint32_t stylesStart;
-};
-
-/**
- * This structure defines a span of style information associated with
- * a string in the pool.
- */
-struct ResStringPool_span
-{
- enum {
- END = 0xFFFFFFFF
- };
-
- // This is the name of the span -- that is, the name of the XML
- // tag that defined it. The special value END (0xFFFFFFFF) indicates
- // the end of an array of spans.
- ResStringPool_ref name;
-
- // The range of characters in the string that this span applies to.
- uint32_t firstChar, lastChar;
-};
-
-/**
- * Convenience class for accessing data in a ResStringPool resource.
- */
-class ResStringPool
-{
-public:
- ResStringPool();
- ResStringPool(const void* data, size_t size, bool copyData=false);
- ~ResStringPool();
-
- status_t setTo(const void* data, size_t size, bool copyData=false);
-
- status_t getError() const;
-
- void uninit();
-
- inline const char16_t* stringAt(const ResStringPool_ref& ref, size_t* outLen) const {
- return stringAt(ref.index, outLen);
- }
- const char16_t* stringAt(size_t idx, size_t* outLen) const;
-
- const char* string8At(size_t idx, size_t* outLen) const;
-
- const ResStringPool_span* styleAt(const ResStringPool_ref& ref) const;
- const ResStringPool_span* styleAt(size_t idx) const;
-
- ssize_t indexOfString(const char16_t* str, size_t strLen) const;
-
- size_t size() const;
-
-#ifndef HAVE_ANDROID_OS
- bool isUTF8() const;
-#endif
-
-private:
- status_t mError;
- void* mOwnedData;
- const ResStringPool_header* mHeader;
- size_t mSize;
- mutable Mutex mDecodeLock;
- const uint32_t* mEntries;
- const uint32_t* mEntryStyles;
- const void* mStrings;
- char16_t** mCache;
- uint32_t mStringPoolSize; // number of uint16_t
- const uint32_t* mStyles;
- uint32_t mStylePoolSize; // number of uint32_t
-};
-
-/** ********************************************************************
- * XML Tree
- *
- * Binary representation of an XML document. This is designed to
- * express everything in an XML document, in a form that is much
- * easier to parse on the device.
- *
- *********************************************************************** */
-
-/**
- * XML tree header. This appears at the front of an XML tree,
- * describing its content. It is followed by a flat array of
- * ResXMLTree_node structures; the hierarchy of the XML document
- * is described by the occurrance of RES_XML_START_ELEMENT_TYPE
- * and corresponding RES_XML_END_ELEMENT_TYPE nodes in the array.
- */
-struct ResXMLTree_header
-{
- struct ResChunk_header header;
-};
-
-/**
- * Basic XML tree node. A single item in the XML document. Extended info
- * about the node can be found after header.headerSize.
- */
-struct ResXMLTree_node
-{
- struct ResChunk_header header;
-
- // Line number in original source file at which this element appeared.
- uint32_t lineNumber;
-
- // Optional XML comment that was associated with this element; -1 if none.
- struct ResStringPool_ref comment;
-};
-
-/**
- * Extended XML tree node for CDATA tags -- includes the CDATA string.
- * Appears header.headerSize bytes after a ResXMLTree_node.
- */
-struct ResXMLTree_cdataExt
-{
- // The raw CDATA character data.
- struct ResStringPool_ref data;
-
- // The typed value of the character data if this is a CDATA node.
- struct Res_value typedData;
-};
-
-/**
- * Extended XML tree node for namespace start/end nodes.
- * Appears header.headerSize bytes after a ResXMLTree_node.
- */
-struct ResXMLTree_namespaceExt
-{
- // The prefix of the namespace.
- struct ResStringPool_ref prefix;
-
- // The URI of the namespace.
- struct ResStringPool_ref uri;
-};
-
-/**
- * Extended XML tree node for element start/end nodes.
- * Appears header.headerSize bytes after a ResXMLTree_node.
- */
-struct ResXMLTree_endElementExt
-{
- // String of the full namespace of this element.
- struct ResStringPool_ref ns;
-
- // String name of this node if it is an ELEMENT; the raw
- // character data if this is a CDATA node.
- struct ResStringPool_ref name;
-};
-
-/**
- * Extended XML tree node for start tags -- includes attribute
- * information.
- * Appears header.headerSize bytes after a ResXMLTree_node.
- */
-struct ResXMLTree_attrExt
-{
- // String of the full namespace of this element.
- struct ResStringPool_ref ns;
-
- // String name of this node if it is an ELEMENT; the raw
- // character data if this is a CDATA node.
- struct ResStringPool_ref name;
-
- // Byte offset from the start of this structure where the attributes start.
- uint16_t attributeStart;
-
- // Size of the ResXMLTree_attribute structures that follow.
- uint16_t attributeSize;
-
- // Number of attributes associated with an ELEMENT. These are
- // available as an array of ResXMLTree_attribute structures
- // immediately following this node.
- uint16_t attributeCount;
-
- // Index (1-based) of the "id" attribute. 0 if none.
- uint16_t idIndex;
-
- // Index (1-based) of the "class" attribute. 0 if none.
- uint16_t classIndex;
-
- // Index (1-based) of the "style" attribute. 0 if none.
- uint16_t styleIndex;
-};
-
-struct ResXMLTree_attribute
-{
- // Namespace of this attribute.
- struct ResStringPool_ref ns;
-
- // Name of this attribute.
- struct ResStringPool_ref name;
-
- // The original raw string value of this attribute.
- struct ResStringPool_ref rawValue;
-
- // Processesd typed value of this attribute.
- struct Res_value typedValue;
-};
-
-class ResXMLTree;
-
-class ResXMLParser
-{
-public:
- ResXMLParser(const ResXMLTree& tree);
-
- enum event_code_t {
- BAD_DOCUMENT = -1,
- START_DOCUMENT = 0,
- END_DOCUMENT = 1,
-
- FIRST_CHUNK_CODE = RES_XML_FIRST_CHUNK_TYPE,
-
- START_NAMESPACE = RES_XML_START_NAMESPACE_TYPE,
- END_NAMESPACE = RES_XML_END_NAMESPACE_TYPE,
- START_TAG = RES_XML_START_ELEMENT_TYPE,
- END_TAG = RES_XML_END_ELEMENT_TYPE,
- TEXT = RES_XML_CDATA_TYPE
- };
-
- struct ResXMLPosition
- {
- event_code_t eventCode;
- const ResXMLTree_node* curNode;
- const void* curExt;
- };
-
- void restart();
-
- const ResStringPool& getStrings() const;
-
- event_code_t getEventType() const;
- // Note, unlike XmlPullParser, the first call to next() will return
- // START_TAG of the first element.
- event_code_t next();
-
- // These are available for all nodes:
- int32_t getCommentID() const;
- const uint16_t* getComment(size_t* outLen) const;
- uint32_t getLineNumber() const;
-
- // This is available for TEXT:
- int32_t getTextID() const;
- const uint16_t* getText(size_t* outLen) const;
- ssize_t getTextValue(Res_value* outValue) const;
-
- // These are available for START_NAMESPACE and END_NAMESPACE:
- int32_t getNamespacePrefixID() const;
- const uint16_t* getNamespacePrefix(size_t* outLen) const;
- int32_t getNamespaceUriID() const;
- const uint16_t* getNamespaceUri(size_t* outLen) const;
-
- // These are available for START_TAG and END_TAG:
- int32_t getElementNamespaceID() const;
- const uint16_t* getElementNamespace(size_t* outLen) const;
- int32_t getElementNameID() const;
- const uint16_t* getElementName(size_t* outLen) const;
-
- // Remaining methods are for retrieving information about attributes
- // associated with a START_TAG:
-
- size_t getAttributeCount() const;
-
- // Returns -1 if no namespace, -2 if idx out of range.
- int32_t getAttributeNamespaceID(size_t idx) const;
- const uint16_t* getAttributeNamespace(size_t idx, size_t* outLen) const;
-
- int32_t getAttributeNameID(size_t idx) const;
- const uint16_t* getAttributeName(size_t idx, size_t* outLen) const;
- uint32_t getAttributeNameResID(size_t idx) const;
-
- int32_t getAttributeValueStringID(size_t idx) const;
- const uint16_t* getAttributeStringValue(size_t idx, size_t* outLen) const;
-
- int32_t getAttributeDataType(size_t idx) const;
- int32_t getAttributeData(size_t idx) const;
- ssize_t getAttributeValue(size_t idx, Res_value* outValue) const;
-
- ssize_t indexOfAttribute(const char* ns, const char* attr) const;
- ssize_t indexOfAttribute(const char16_t* ns, size_t nsLen,
- const char16_t* attr, size_t attrLen) const;
-
- ssize_t indexOfID() const;
- ssize_t indexOfClass() const;
- ssize_t indexOfStyle() const;
-
- void getPosition(ResXMLPosition* pos) const;
- void setPosition(const ResXMLPosition& pos);
-
-private:
- friend class ResXMLTree;
-
- event_code_t nextNode();
-
- const ResXMLTree& mTree;
- event_code_t mEventCode;
- const ResXMLTree_node* mCurNode;
- const void* mCurExt;
-};
-
-/**
- * Convenience class for accessing data in a ResXMLTree resource.
- */
-class ResXMLTree : public ResXMLParser
-{
-public:
- ResXMLTree();
- ResXMLTree(const void* data, size_t size, bool copyData=false);
- ~ResXMLTree();
-
- status_t setTo(const void* data, size_t size, bool copyData=false);
-
- status_t getError() const;
-
- void uninit();
-
-private:
- friend class ResXMLParser;
-
- status_t validateNode(const ResXMLTree_node* node) const;
-
- status_t mError;
- void* mOwnedData;
- const ResXMLTree_header* mHeader;
- size_t mSize;
- const uint8_t* mDataEnd;
- ResStringPool mStrings;
- const uint32_t* mResIds;
- size_t mNumResIds;
- const ResXMLTree_node* mRootNode;
- const void* mRootExt;
- event_code_t mRootCode;
-};
-
-/** ********************************************************************
- * RESOURCE TABLE
- *
- *********************************************************************** */
-
-/**
- * Header for a resource table. Its data contains a series of
- * additional chunks:
- * * A ResStringPool_header containing all table values.
- * * One or more ResTable_package chunks.
- *
- * Specific entries within a resource table can be uniquely identified
- * with a single integer as defined by the ResTable_ref structure.
- */
-struct ResTable_header
-{
- struct ResChunk_header header;
-
- // The number of ResTable_package structures.
- uint32_t packageCount;
-};
-
-/**
- * A collection of resource data types within a package. Followed by
- * one or more ResTable_type and ResTable_typeSpec structures containing the
- * entry values for each resource type.
- */
-struct ResTable_package
-{
- struct ResChunk_header header;
-
- // If this is a base package, its ID. Package IDs start
- // at 1 (corresponding to the value of the package bits in a
- // resource identifier). 0 means this is not a base package.
- uint32_t id;
-
- // Actual name of this package, \0-terminated.
- char16_t name[128];
-
- // Offset to a ResStringPool_header defining the resource
- // type symbol table. If zero, this package is inheriting from
- // another base package (overriding specific values in it).
- uint32_t typeStrings;
-
- // Last index into typeStrings that is for public use by others.
- uint32_t lastPublicType;
-
- // Offset to a ResStringPool_header defining the resource
- // key symbol table. If zero, this package is inheriting from
- // another base package (overriding specific values in it).
- uint32_t keyStrings;
-
- // Last index into keyStrings that is for public use by others.
- uint32_t lastPublicKey;
-};
-
-/**
- * Describes a particular resource configuration.
- */
-struct ResTable_config
-{
- // Number of bytes in this structure.
- uint32_t size;
-
- union {
- struct {
- // Mobile country code (from SIM). 0 means "any".
- uint16_t mcc;
- // Mobile network code (from SIM). 0 means "any".
- uint16_t mnc;
- };
- uint32_t imsi;
- };
-
- union {
- struct {
- // \0\0 means "any". Otherwise, en, fr, etc.
- char language[2];
-
- // \0\0 means "any". Otherwise, US, CA, etc.
- char country[2];
- };
- uint32_t locale;
- };
-
- enum {
- ORIENTATION_ANY = ACONFIGURATION_ORIENTATION_ANY,
- ORIENTATION_PORT = ACONFIGURATION_ORIENTATION_PORT,
- ORIENTATION_LAND = ACONFIGURATION_ORIENTATION_LAND,
- ORIENTATION_SQUARE = ACONFIGURATION_ORIENTATION_SQUARE,
- };
-
- enum {
- TOUCHSCREEN_ANY = ACONFIGURATION_TOUCHSCREEN_ANY,
- TOUCHSCREEN_NOTOUCH = ACONFIGURATION_TOUCHSCREEN_NOTOUCH,
- TOUCHSCREEN_STYLUS = ACONFIGURATION_TOUCHSCREEN_STYLUS,
- TOUCHSCREEN_FINGER = ACONFIGURATION_TOUCHSCREEN_FINGER,
- };
-
- enum {
- DENSITY_DEFAULT = ACONFIGURATION_DENSITY_DEFAULT,
- DENSITY_LOW = ACONFIGURATION_DENSITY_LOW,
- DENSITY_MEDIUM = ACONFIGURATION_DENSITY_MEDIUM,
- DENSITY_TV = ACONFIGURATION_DENSITY_TV,
- DENSITY_HIGH = ACONFIGURATION_DENSITY_HIGH,
- DENSITY_NONE = ACONFIGURATION_DENSITY_NONE
- };
-
- union {
- struct {
- uint8_t orientation;
- uint8_t touchscreen;
- uint16_t density;
- };
- uint32_t screenType;
- };
-
- enum {
- KEYBOARD_ANY = ACONFIGURATION_KEYBOARD_ANY,
- KEYBOARD_NOKEYS = ACONFIGURATION_KEYBOARD_NOKEYS,
- KEYBOARD_QWERTY = ACONFIGURATION_KEYBOARD_QWERTY,
- KEYBOARD_12KEY = ACONFIGURATION_KEYBOARD_12KEY,
- };
-
- enum {
- NAVIGATION_ANY = ACONFIGURATION_NAVIGATION_ANY,
- NAVIGATION_NONAV = ACONFIGURATION_NAVIGATION_NONAV,
- NAVIGATION_DPAD = ACONFIGURATION_NAVIGATION_DPAD,
- NAVIGATION_TRACKBALL = ACONFIGURATION_NAVIGATION_TRACKBALL,
- NAVIGATION_WHEEL = ACONFIGURATION_NAVIGATION_WHEEL,
- };
-
- enum {
- MASK_KEYSHIDDEN = 0x0003,
- KEYSHIDDEN_ANY = ACONFIGURATION_KEYSHIDDEN_ANY,
- KEYSHIDDEN_NO = ACONFIGURATION_KEYSHIDDEN_NO,
- KEYSHIDDEN_YES = ACONFIGURATION_KEYSHIDDEN_YES,
- KEYSHIDDEN_SOFT = ACONFIGURATION_KEYSHIDDEN_SOFT,
- };
-
- enum {
- MASK_NAVHIDDEN = 0x000c,
- SHIFT_NAVHIDDEN = 2,
- NAVHIDDEN_ANY = ACONFIGURATION_NAVHIDDEN_ANY << SHIFT_NAVHIDDEN,
- NAVHIDDEN_NO = ACONFIGURATION_NAVHIDDEN_NO << SHIFT_NAVHIDDEN,
- NAVHIDDEN_YES = ACONFIGURATION_NAVHIDDEN_YES << SHIFT_NAVHIDDEN,
- };
-
- union {
- struct {
- uint8_t keyboard;
- uint8_t navigation;
- uint8_t inputFlags;
- uint8_t inputPad0;
- };
- uint32_t input;
- };
-
- enum {
- SCREENWIDTH_ANY = 0
- };
-
- enum {
- SCREENHEIGHT_ANY = 0
- };
-
- union {
- struct {
- uint16_t screenWidth;
- uint16_t screenHeight;
- };
- uint32_t screenSize;
- };
-
- enum {
- SDKVERSION_ANY = 0
- };
-
- enum {
- MINORVERSION_ANY = 0
- };
-
- union {
- struct {
- uint16_t sdkVersion;
- // For now minorVersion must always be 0!!! Its meaning
- // is currently undefined.
- uint16_t minorVersion;
- };
- uint32_t version;
- };
-
- enum {
- // screenLayout bits for screen size class.
- MASK_SCREENSIZE = 0x0f,
- SCREENSIZE_ANY = ACONFIGURATION_SCREENSIZE_ANY,
- SCREENSIZE_SMALL = ACONFIGURATION_SCREENSIZE_SMALL,
- SCREENSIZE_NORMAL = ACONFIGURATION_SCREENSIZE_NORMAL,
- SCREENSIZE_LARGE = ACONFIGURATION_SCREENSIZE_LARGE,
- SCREENSIZE_XLARGE = ACONFIGURATION_SCREENSIZE_XLARGE,
-
- // screenLayout bits for wide/long screen variation.
- MASK_SCREENLONG = 0x30,
- SHIFT_SCREENLONG = 4,
- SCREENLONG_ANY = ACONFIGURATION_SCREENLONG_ANY << SHIFT_SCREENLONG,
- SCREENLONG_NO = ACONFIGURATION_SCREENLONG_NO << SHIFT_SCREENLONG,
- SCREENLONG_YES = ACONFIGURATION_SCREENLONG_YES << SHIFT_SCREENLONG,
- };
-
- enum {
- // uiMode bits for the mode type.
- MASK_UI_MODE_TYPE = 0x0f,
- UI_MODE_TYPE_ANY = ACONFIGURATION_UI_MODE_TYPE_ANY,
- UI_MODE_TYPE_NORMAL = ACONFIGURATION_UI_MODE_TYPE_NORMAL,
- UI_MODE_TYPE_DESK = ACONFIGURATION_UI_MODE_TYPE_DESK,
- UI_MODE_TYPE_CAR = ACONFIGURATION_UI_MODE_TYPE_CAR,
- UI_MODE_TYPE_TELEVISION = ACONFIGURATION_UI_MODE_TYPE_TELEVISION,
-
- // uiMode bits for the night switch.
- MASK_UI_MODE_NIGHT = 0x30,
- SHIFT_UI_MODE_NIGHT = 4,
- UI_MODE_NIGHT_ANY = ACONFIGURATION_UI_MODE_NIGHT_ANY << SHIFT_UI_MODE_NIGHT,
- UI_MODE_NIGHT_NO = ACONFIGURATION_UI_MODE_NIGHT_NO << SHIFT_UI_MODE_NIGHT,
- UI_MODE_NIGHT_YES = ACONFIGURATION_UI_MODE_NIGHT_YES << SHIFT_UI_MODE_NIGHT,
- };
-
- union {
- struct {
- uint8_t screenLayout;
- uint8_t uiMode;
- uint16_t smallestScreenWidthDp;
- };
- uint32_t screenConfig;
- };
-
- union {
- struct {
- uint16_t screenWidthDp;
- uint16_t screenHeightDp;
- };
- uint32_t screenSizeDp;
- };
-
- inline void copyFromDeviceNoSwap(const ResTable_config& o) {
- const size_t size = dtohl(o.size);
- if (size >= sizeof(ResTable_config)) {
- *this = o;
- } else {
- memcpy(this, &o, size);
- memset(((uint8_t*)this)+size, 0, sizeof(ResTable_config)-size);
- }
- }
-
- inline void copyFromDtoH(const ResTable_config& o) {
- copyFromDeviceNoSwap(o);
- size = sizeof(ResTable_config);
- mcc = dtohs(mcc);
- mnc = dtohs(mnc);
- density = dtohs(density);
- screenWidth = dtohs(screenWidth);
- screenHeight = dtohs(screenHeight);
- sdkVersion = dtohs(sdkVersion);
- minorVersion = dtohs(minorVersion);
- smallestScreenWidthDp = dtohs(smallestScreenWidthDp);
- screenWidthDp = dtohs(screenWidthDp);
- screenHeightDp = dtohs(screenHeightDp);
- }
-
- inline void swapHtoD() {
- size = htodl(size);
- mcc = htods(mcc);
- mnc = htods(mnc);
- density = htods(density);
- screenWidth = htods(screenWidth);
- screenHeight = htods(screenHeight);
- sdkVersion = htods(sdkVersion);
- minorVersion = htods(minorVersion);
- smallestScreenWidthDp = htods(smallestScreenWidthDp);
- screenWidthDp = htods(screenWidthDp);
- screenHeightDp = htods(screenHeightDp);
- }
-
- inline int compare(const ResTable_config& o) const {
- int32_t diff = (int32_t)(imsi - o.imsi);
- if (diff != 0) return diff;
- diff = (int32_t)(locale - o.locale);
- if (diff != 0) return diff;
- diff = (int32_t)(screenType - o.screenType);
- if (diff != 0) return diff;
- diff = (int32_t)(input - o.input);
- if (diff != 0) return diff;
- diff = (int32_t)(screenSize - o.screenSize);
- if (diff != 0) return diff;
- diff = (int32_t)(version - o.version);
- if (diff != 0) return diff;
- diff = (int32_t)(screenLayout - o.screenLayout);
- if (diff != 0) return diff;
- diff = (int32_t)(uiMode - o.uiMode);
- if (diff != 0) return diff;
- diff = (int32_t)(smallestScreenWidthDp - o.smallestScreenWidthDp);
- if (diff != 0) return diff;
- diff = (int32_t)(screenSizeDp - o.screenSizeDp);
- return (int)diff;
- }
-
- // Flags indicating a set of config values. These flag constants must
- // match the corresponding ones in android.content.pm.ActivityInfo and
- // attrs_manifest.xml.
- enum {
- CONFIG_MCC = ACONFIGURATION_MCC,
- CONFIG_MNC = ACONFIGURATION_MCC,
- CONFIG_LOCALE = ACONFIGURATION_LOCALE,
- CONFIG_TOUCHSCREEN = ACONFIGURATION_TOUCHSCREEN,
- CONFIG_KEYBOARD = ACONFIGURATION_KEYBOARD,
- CONFIG_KEYBOARD_HIDDEN = ACONFIGURATION_KEYBOARD_HIDDEN,
- CONFIG_NAVIGATION = ACONFIGURATION_NAVIGATION,
- CONFIG_ORIENTATION = ACONFIGURATION_ORIENTATION,
- CONFIG_DENSITY = ACONFIGURATION_DENSITY,
- CONFIG_SCREEN_SIZE = ACONFIGURATION_SCREEN_SIZE,
- CONFIG_SMALLEST_SCREEN_SIZE = ACONFIGURATION_SMALLEST_SCREEN_SIZE,
- CONFIG_VERSION = ACONFIGURATION_VERSION,
- CONFIG_SCREEN_LAYOUT = ACONFIGURATION_SCREEN_LAYOUT,
- CONFIG_UI_MODE = ACONFIGURATION_UI_MODE
- };
-
- // Compare two configuration, returning CONFIG_* flags set for each value
- // that is different.
- inline int diff(const ResTable_config& o) const {
- int diffs = 0;
- if (mcc != o.mcc) diffs |= CONFIG_MCC;
- if (mnc != o.mnc) diffs |= CONFIG_MNC;
- if (locale != o.locale) diffs |= CONFIG_LOCALE;
- if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION;
- if (density != o.density) diffs |= CONFIG_DENSITY;
- if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN;
- if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0)
- diffs |= CONFIG_KEYBOARD_HIDDEN;
- if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD;
- if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION;
- if (screenSize != o.screenSize) diffs |= CONFIG_SCREEN_SIZE;
- if (version != o.version) diffs |= CONFIG_VERSION;
- if (screenLayout != o.screenLayout) diffs |= CONFIG_SCREEN_LAYOUT;
- if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE;
- if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE;
- if (screenSizeDp != o.screenSizeDp) diffs |= CONFIG_SCREEN_SIZE;
- return diffs;
- }
-
- // Return true if 'this' is more specific than 'o'.
- inline bool
- isMoreSpecificThan(const ResTable_config& o) const {
- // The order of the following tests defines the importance of one
- // configuration parameter over another. Those tests first are more
- // important, trumping any values in those following them.
- if (imsi || o.imsi) {
- if (mcc != o.mcc) {
- if (!mcc) return false;
- if (!o.mcc) return true;
- }
-
- if (mnc != o.mnc) {
- if (!mnc) return false;
- if (!o.mnc) return true;
- }
- }
-
- if (locale || o.locale) {
- if (language[0] != o.language[0]) {
- if (!language[0]) return false;
- if (!o.language[0]) return true;
- }
-
- if (country[0] != o.country[0]) {
- if (!country[0]) return false;
- if (!o.country[0]) return true;
- }
- }
-
- if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
- if (smallestScreenWidthDp != o.smallestScreenWidthDp) {
- if (!smallestScreenWidthDp) return false;
- if (!o.smallestScreenWidthDp) return true;
- }
- }
-
- if (screenSizeDp || o.screenSizeDp) {
- if (screenWidthDp != o.screenWidthDp) {
- if (!screenWidthDp) return false;
- if (!o.screenWidthDp) return true;
- }
-
- if (screenHeightDp != o.screenHeightDp) {
- if (!screenHeightDp) return false;
- if (!o.screenHeightDp) return true;
- }
- }
-
- if (screenLayout || o.screenLayout) {
- if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0) {
- if (!(screenLayout & MASK_SCREENSIZE)) return false;
- if (!(o.screenLayout & MASK_SCREENSIZE)) return true;
- }
- if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0) {
- if (!(screenLayout & MASK_SCREENLONG)) return false;
- if (!(o.screenLayout & MASK_SCREENLONG)) return true;
- }
- }
-
- if (orientation != o.orientation) {
- if (!orientation) return false;
- if (!o.orientation) return true;
- }
-
- if (uiMode || o.uiMode) {
- if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0) {
- if (!(uiMode & MASK_UI_MODE_TYPE)) return false;
- if (!(o.uiMode & MASK_UI_MODE_TYPE)) return true;
- }
- if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0) {
- if (!(uiMode & MASK_UI_MODE_NIGHT)) return false;
- if (!(o.uiMode & MASK_UI_MODE_NIGHT)) return true;
- }
- }
-
- // density is never 'more specific'
- // as the default just equals 160
-
- if (touchscreen != o.touchscreen) {
- if (!touchscreen) return false;
- if (!o.touchscreen) return true;
- }
-
- if (input || o.input) {
- if (((inputFlags^o.inputFlags) & MASK_KEYSHIDDEN) != 0) {
- if (!(inputFlags & MASK_KEYSHIDDEN)) return false;
- if (!(o.inputFlags & MASK_KEYSHIDDEN)) return true;
- }
-
- if (((inputFlags^o.inputFlags) & MASK_NAVHIDDEN) != 0) {
- if (!(inputFlags & MASK_NAVHIDDEN)) return false;
- if (!(o.inputFlags & MASK_NAVHIDDEN)) return true;
- }
-
- if (keyboard != o.keyboard) {
- if (!keyboard) return false;
- if (!o.keyboard) return true;
- }
-
- if (navigation != o.navigation) {
- if (!navigation) return false;
- if (!o.navigation) return true;
- }
- }
-
- if (screenSize || o.screenSize) {
- if (screenWidth != o.screenWidth) {
- if (!screenWidth) return false;
- if (!o.screenWidth) return true;
- }
-
- if (screenHeight != o.screenHeight) {
- if (!screenHeight) return false;
- if (!o.screenHeight) return true;
- }
- }
-
- if (version || o.version) {
- if (sdkVersion != o.sdkVersion) {
- if (!sdkVersion) return false;
- if (!o.sdkVersion) return true;
- }
-
- if (minorVersion != o.minorVersion) {
- if (!minorVersion) return false;
- if (!o.minorVersion) return true;
- }
- }
- return false;
- }
-
- // Return true if 'this' is a better match than 'o' for the 'requested'
- // configuration. This assumes that match() has already been used to
- // remove any configurations that don't match the requested configuration
- // at all; if they are not first filtered, non-matching results can be
- // considered better than matching ones.
- // The general rule per attribute: if the request cares about an attribute
- // (it normally does), if the two (this and o) are equal it's a tie. If
- // they are not equal then one must be generic because only generic and
- // '==requested' will pass the match() call. So if this is not generic,
- // it wins. If this IS generic, o wins (return false).
- inline bool
- isBetterThan(const ResTable_config& o,
- const ResTable_config* requested) const {
- if (requested) {
- if (imsi || o.imsi) {
- if ((mcc != o.mcc) && requested->mcc) {
- return (mcc);
- }
-
- if ((mnc != o.mnc) && requested->mnc) {
- return (mnc);
- }
- }
-
- if (locale || o.locale) {
- if ((language[0] != o.language[0]) && requested->language[0]) {
- return (language[0]);
- }
-
- if ((country[0] != o.country[0]) && requested->country[0]) {
- return (country[0]);
- }
- }
-
- if (smallestScreenWidthDp || o.smallestScreenWidthDp) {
- // The configuration closest to the actual size is best.
- // We assume that larger configs have already been filtered
- // out at this point. That means we just want the largest one.
- return smallestScreenWidthDp >= o.smallestScreenWidthDp;
- }
-
- if (screenSizeDp || o.screenSizeDp) {
- // "Better" is based on the sum of the difference between both
- // width and height from the requested dimensions. We are
- // assuming the invalid configs (with smaller dimens) have
- // already been filtered. Note that if a particular dimension
- // is unspecified, we will end up with a large value (the
- // difference between 0 and the requested dimension), which is
- // good since we will prefer a config that has specified a
- // dimension value.
- int myDelta = 0, otherDelta = 0;
- if (requested->screenWidthDp) {
- myDelta += requested->screenWidthDp - screenWidthDp;
- otherDelta += requested->screenWidthDp - o.screenWidthDp;
- }
- if (requested->screenHeightDp) {
- myDelta += requested->screenHeightDp - screenHeightDp;
- otherDelta += requested->screenHeightDp - o.screenHeightDp;
- }
- //ALOGI("Comparing this %dx%d to other %dx%d in %dx%d: myDelta=%d otherDelta=%d",
- // screenWidthDp, screenHeightDp, o.screenWidthDp, o.screenHeightDp,
- // requested->screenWidthDp, requested->screenHeightDp, myDelta, otherDelta);
- return (myDelta <= otherDelta);
- }
-
- if (screenLayout || o.screenLayout) {
- if (((screenLayout^o.screenLayout) & MASK_SCREENSIZE) != 0
- && (requested->screenLayout & MASK_SCREENSIZE)) {
- // A little backwards compatibility here: undefined is
- // considered equivalent to normal. But only if the
- // requested size is at least normal; otherwise, small
- // is better than the default.
- int mySL = (screenLayout & MASK_SCREENSIZE);
- int oSL = (o.screenLayout & MASK_SCREENSIZE);
- int fixedMySL = mySL;
- int fixedOSL = oSL;
- if ((requested->screenLayout & MASK_SCREENSIZE) >= SCREENSIZE_NORMAL) {
- if (fixedMySL == 0) fixedMySL = SCREENSIZE_NORMAL;
- if (fixedOSL == 0) fixedOSL = SCREENSIZE_NORMAL;
- }
- // For screen size, the best match is the one that is
- // closest to the requested screen size, but not over
- // (the not over part is dealt with in match() below).
- if (fixedMySL == fixedOSL) {
- // If the two are the same, but 'this' is actually
- // undefined, then the other is really a better match.
- if (mySL == 0) return false;
- return true;
- }
- return fixedMySL >= fixedOSL;
- }
- if (((screenLayout^o.screenLayout) & MASK_SCREENLONG) != 0
- && (requested->screenLayout & MASK_SCREENLONG)) {
- return (screenLayout & MASK_SCREENLONG);
- }
- }
-
- if ((orientation != o.orientation) && requested->orientation) {
- return (orientation);
- }
-
- if (uiMode || o.uiMode) {
- if (((uiMode^o.uiMode) & MASK_UI_MODE_TYPE) != 0
- && (requested->uiMode & MASK_UI_MODE_TYPE)) {
- return (uiMode & MASK_UI_MODE_TYPE);
- }
- if (((uiMode^o.uiMode) & MASK_UI_MODE_NIGHT) != 0
- && (requested->uiMode & MASK_UI_MODE_NIGHT)) {
- return (uiMode & MASK_UI_MODE_NIGHT);
- }
- }
-
- if (screenType || o.screenType) {
- if (density != o.density) {
- // density is tough. Any density is potentially useful
- // because the system will scale it. Scaling down
- // is generally better than scaling up.
- // Default density counts as 160dpi (the system default)
- // TODO - remove 160 constants
- int h = (density?density:160);
- int l = (o.density?o.density:160);
- bool bImBigger = true;
- if (l > h) {
- int t = h;
- h = l;
- l = t;
- bImBigger = false;
- }
-
- int reqValue = (requested->density?requested->density:160);
- if (reqValue >= h) {
- // requested value higher than both l and h, give h
- return bImBigger;
- }
- if (l >= reqValue) {
- // requested value lower than both l and h, give l
- return !bImBigger;
- }
- // saying that scaling down is 2x better than up
- if (((2 * l) - reqValue) * h > reqValue * reqValue) {
- return !bImBigger;
- } else {
- return bImBigger;
- }
- }
-
- if ((touchscreen != o.touchscreen) && requested->touchscreen) {
- return (touchscreen);
- }
- }
-
- if (input || o.input) {
- const int keysHidden = inputFlags & MASK_KEYSHIDDEN;
- const int oKeysHidden = o.inputFlags & MASK_KEYSHIDDEN;
- if (keysHidden != oKeysHidden) {
- const int reqKeysHidden =
- requested->inputFlags & MASK_KEYSHIDDEN;
- if (reqKeysHidden) {
-
- if (!keysHidden) return false;
- if (!oKeysHidden) return true;
- // For compatibility, we count KEYSHIDDEN_NO as being
- // the same as KEYSHIDDEN_SOFT. Here we disambiguate
- // these by making an exact match more specific.
- if (reqKeysHidden == keysHidden) return true;
- if (reqKeysHidden == oKeysHidden) return false;
- }
- }
-
- const int navHidden = inputFlags & MASK_NAVHIDDEN;
- const int oNavHidden = o.inputFlags & MASK_NAVHIDDEN;
- if (navHidden != oNavHidden) {
- const int reqNavHidden =
- requested->inputFlags & MASK_NAVHIDDEN;
- if (reqNavHidden) {
-
- if (!navHidden) return false;
- if (!oNavHidden) return true;
- }
- }
-
- if ((keyboard != o.keyboard) && requested->keyboard) {
- return (keyboard);
- }
-
- if ((navigation != o.navigation) && requested->navigation) {
- return (navigation);
- }
- }
-
- if (screenSize || o.screenSize) {
- // "Better" is based on the sum of the difference between both
- // width and height from the requested dimensions. We are
- // assuming the invalid configs (with smaller sizes) have
- // already been filtered. Note that if a particular dimension
- // is unspecified, we will end up with a large value (the
- // difference between 0 and the requested dimension), which is
- // good since we will prefer a config that has specified a
- // size value.
- int myDelta = 0, otherDelta = 0;
- if (requested->screenWidth) {
- myDelta += requested->screenWidth - screenWidth;
- otherDelta += requested->screenWidth - o.screenWidth;
- }
- if (requested->screenHeight) {
- myDelta += requested->screenHeight - screenHeight;
- otherDelta += requested->screenHeight - o.screenHeight;
- }
- return (myDelta <= otherDelta);
- }
-
- if (version || o.version) {
- if ((sdkVersion != o.sdkVersion) && requested->sdkVersion) {
- return (sdkVersion > o.sdkVersion);
- }
-
- if ((minorVersion != o.minorVersion) &&
- requested->minorVersion) {
- return (minorVersion);
- }
- }
-
- return false;
- }
- return isMoreSpecificThan(o);
- }
-
- // Return true if 'this' can be considered a match for the parameters in
- // 'settings'.
- // Note this is asymetric. A default piece of data will match every request
- // but a request for the default should not match odd specifics
- // (ie, request with no mcc should not match a particular mcc's data)
- // settings is the requested settings
- inline bool match(const ResTable_config& settings) const {
- if (imsi != 0) {
- if (mcc != 0 && mcc != settings.mcc) {
- return false;
- }
- if (mnc != 0 && mnc != settings.mnc) {
- return false;
- }
- }
- if (locale != 0) {
- if (language[0] != 0
- && (language[0] != settings.language[0]
- || language[1] != settings.language[1])) {
- return false;
- }
- if (country[0] != 0
- && (country[0] != settings.country[0]
- || country[1] != settings.country[1])) {
- return false;
- }
- }
- if (screenConfig != 0) {
- const int screenSize = screenLayout&MASK_SCREENSIZE;
- const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE;
- // Any screen sizes for larger screens than the setting do not
- // match.
- if (screenSize != 0 && screenSize > setScreenSize) {
- return false;
- }
-
- const int screenLong = screenLayout&MASK_SCREENLONG;
- const int setScreenLong = settings.screenLayout&MASK_SCREENLONG;
- if (screenLong != 0 && screenLong != setScreenLong) {
- return false;
- }
-
- const int uiModeType = uiMode&MASK_UI_MODE_TYPE;
- const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE;
- if (uiModeType != 0 && uiModeType != setUiModeType) {
- return false;
- }
-
- const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT;
- const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT;
- if (uiModeNight != 0 && uiModeNight != setUiModeNight) {
- return false;
- }
-
- if (smallestScreenWidthDp != 0
- && smallestScreenWidthDp > settings.smallestScreenWidthDp) {
- return false;
- }
- }
- if (screenSizeDp != 0) {
- if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) {
- //ALOGI("Filtering out width %d in requested %d", screenWidthDp, settings.screenWidthDp);
- return false;
- }
- if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) {
- //ALOGI("Filtering out height %d in requested %d", screenHeightDp, settings.screenHeightDp);
- return false;
- }
- }
- if (screenType != 0) {
- if (orientation != 0 && orientation != settings.orientation) {
- return false;
- }
- // density always matches - we can scale it. See isBetterThan
- if (touchscreen != 0 && touchscreen != settings.touchscreen) {
- return false;
- }
- }
- if (input != 0) {
- const int keysHidden = inputFlags&MASK_KEYSHIDDEN;
- const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN;
- if (keysHidden != 0 && keysHidden != setKeysHidden) {
- // For compatibility, we count a request for KEYSHIDDEN_NO as also
- // matching the more recent KEYSHIDDEN_SOFT. Basically
- // KEYSHIDDEN_NO means there is some kind of keyboard available.
- //ALOGI("Matching keysHidden: have=%d, config=%d\n", keysHidden, setKeysHidden);
- if (keysHidden != KEYSHIDDEN_NO || setKeysHidden != KEYSHIDDEN_SOFT) {
- //ALOGI("No match!");
- return false;
- }
- }
- const int navHidden = inputFlags&MASK_NAVHIDDEN;
- const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN;
- if (navHidden != 0 && navHidden != setNavHidden) {
- return false;
- }
- if (keyboard != 0 && keyboard != settings.keyboard) {
- return false;
- }
- if (navigation != 0 && navigation != settings.navigation) {
- return false;
- }
- }
- if (screenSize != 0) {
- if (screenWidth != 0 && screenWidth > settings.screenWidth) {
- return false;
- }
- if (screenHeight != 0 && screenHeight > settings.screenHeight) {
- return false;
- }
- }
- if (version != 0) {
- if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) {
- return false;
- }
- if (minorVersion != 0 && minorVersion != settings.minorVersion) {
- return false;
- }
- }
- return true;
- }
-
- void getLocale(char str[6]) const {
- memset(str, 0, 6);
- if (language[0]) {
- str[0] = language[0];
- str[1] = language[1];
- if (country[0]) {
- str[2] = '_';
- str[3] = country[0];
- str[4] = country[1];
- }
- }
- }
-
- String8 toString() const {
- char buf[200];
- sprintf(buf, "imsi=%d/%d lang=%c%c reg=%c%c orient=%d touch=%d dens=%d "
- "kbd=%d nav=%d input=%d ssz=%dx%d sw%ddp w%ddp h%ddp sz=%d long=%d "
- "ui=%d night=%d vers=%d.%d",
- mcc, mnc,
- language[0] ? language[0] : '-', language[1] ? language[1] : '-',
- country[0] ? country[0] : '-', country[1] ? country[1] : '-',
- orientation, touchscreen, density, keyboard, navigation, inputFlags,
- screenWidth, screenHeight, smallestScreenWidthDp, screenWidthDp, screenHeightDp,
- screenLayout&MASK_SCREENSIZE, screenLayout&MASK_SCREENLONG,
- uiMode&MASK_UI_MODE_TYPE, uiMode&MASK_UI_MODE_NIGHT,
- sdkVersion, minorVersion);
- return String8(buf);
- }
-};
-
-/**
- * A specification of the resources defined by a particular type.
- *
- * There should be one of these chunks for each resource type.
- *
- * This structure is followed by an array of integers providing the set of
- * configuation change flags (ResTable_config::CONFIG_*) that have multiple
- * resources for that configuration. In addition, the high bit is set if that
- * resource has been made public.
- */
-struct ResTable_typeSpec
-{
- struct ResChunk_header header;
-
- // The type identifier this chunk is holding. Type IDs start
- // at 1 (corresponding to the value of the type bits in a
- // resource identifier). 0 is invalid.
- uint8_t id;
-
- // Must be 0.
- uint8_t res0;
- // Must be 0.
- uint16_t res1;
-
- // Number of uint32_t entry configuration masks that follow.
- uint32_t entryCount;
-
- enum {
- // Additional flag indicating an entry is public.
- SPEC_PUBLIC = 0x40000000
- };
-};
-
-/**
- * A collection of resource entries for a particular resource data
- * type. Followed by an array of uint32_t defining the resource
- * values, corresponding to the array of type strings in the
- * ResTable_package::typeStrings string block. Each of these hold an
- * index from entriesStart; a value of NO_ENTRY means that entry is
- * not defined.
- *
- * There may be multiple of these chunks for a particular resource type,
- * supply different configuration variations for the resource values of
- * that type.
- *
- * It would be nice to have an additional ordered index of entries, so
- * we can do a binary search if trying to find a resource by string name.
- */
-struct ResTable_type
-{
- struct ResChunk_header header;
-
- enum {
- NO_ENTRY = 0xFFFFFFFF
- };
-
- // The type identifier this chunk is holding. Type IDs start
- // at 1 (corresponding to the value of the type bits in a
- // resource identifier). 0 is invalid.
- uint8_t id;
-
- // Must be 0.
- uint8_t res0;
- // Must be 0.
- uint16_t res1;
-
- // Number of uint32_t entry indices that follow.
- uint32_t entryCount;
-
- // Offset from header where ResTable_entry data starts.
- uint32_t entriesStart;
-
- // Configuration this collection of entries is designed for.
- ResTable_config config;
-};
-
-/**
- * This is the beginning of information about an entry in the resource
- * table. It holds the reference to the name of this entry, and is
- * immediately followed by one of:
- * * A Res_value structure, if FLAG_COMPLEX is -not- set.
- * * An array of ResTable_map structures, if FLAG_COMPLEX is set.
- * These supply a set of name/value mappings of data.
- */
-struct ResTable_entry
-{
- // Number of bytes in this structure.
- uint16_t size;
-
- enum {
- // If set, this is a complex entry, holding a set of name/value
- // mappings. It is followed by an array of ResTable_map structures.
- FLAG_COMPLEX = 0x0001,
- // If set, this resource has been declared public, so libraries
- // are allowed to reference it.
- FLAG_PUBLIC = 0x0002
- };
- uint16_t flags;
-
- // Reference into ResTable_package::keyStrings identifying this entry.
- struct ResStringPool_ref key;
-};
-
-/**
- * Extended form of a ResTable_entry for map entries, defining a parent map
- * resource from which to inherit values.
- */
-struct ResTable_map_entry : public ResTable_entry
-{
- // Resource identifier of the parent mapping, or 0 if there is none.
- ResTable_ref parent;
- // Number of name/value pairs that follow for FLAG_COMPLEX.
- uint32_t count;
-};
-
-/**
- * A single name/value mapping that is part of a complex resource
- * entry.
- */
-struct ResTable_map
-{
- // The resource identifier defining this mapping's name. For attribute
- // resources, 'name' can be one of the following special resource types
- // to supply meta-data about the attribute; for all other resource types
- // it must be an attribute resource.
- ResTable_ref name;
-
- // Special values for 'name' when defining attribute resources.
- enum {
- // This entry holds the attribute's type code.
- ATTR_TYPE = Res_MAKEINTERNAL(0),
-
- // For integral attributes, this is the minimum value it can hold.
- ATTR_MIN = Res_MAKEINTERNAL(1),
-
- // For integral attributes, this is the maximum value it can hold.
- ATTR_MAX = Res_MAKEINTERNAL(2),
-
- // Localization of this resource is can be encouraged or required with
- // an aapt flag if this is set
- ATTR_L10N = Res_MAKEINTERNAL(3),
-
- // for plural support, see android.content.res.PluralRules#attrForQuantity(int)
- ATTR_OTHER = Res_MAKEINTERNAL(4),
- ATTR_ZERO = Res_MAKEINTERNAL(5),
- ATTR_ONE = Res_MAKEINTERNAL(6),
- ATTR_TWO = Res_MAKEINTERNAL(7),
- ATTR_FEW = Res_MAKEINTERNAL(8),
- ATTR_MANY = Res_MAKEINTERNAL(9)
-
- };
-
- // Bit mask of allowed types, for use with ATTR_TYPE.
- enum {
- // No type has been defined for this attribute, use generic
- // type handling. The low 16 bits are for types that can be
- // handled generically; the upper 16 require additional information
- // in the bag so can not be handled generically for TYPE_ANY.
- TYPE_ANY = 0x0000FFFF,
-
- // Attribute holds a references to another resource.
- TYPE_REFERENCE = 1<<0,
-
- // Attribute holds a generic string.
- TYPE_STRING = 1<<1,
-
- // Attribute holds an integer value. ATTR_MIN and ATTR_MIN can
- // optionally specify a constrained range of possible integer values.
- TYPE_INTEGER = 1<<2,
-
- // Attribute holds a boolean integer.
- TYPE_BOOLEAN = 1<<3,
-
- // Attribute holds a color value.
- TYPE_COLOR = 1<<4,
-
- // Attribute holds a floating point value.
- TYPE_FLOAT = 1<<5,
-
- // Attribute holds a dimension value, such as "20px".
- TYPE_DIMENSION = 1<<6,
-
- // Attribute holds a fraction value, such as "20%".
- TYPE_FRACTION = 1<<7,
-
- // Attribute holds an enumeration. The enumeration values are
- // supplied as additional entries in the map.
- TYPE_ENUM = 1<<16,
-
- // Attribute holds a bitmaks of flags. The flag bit values are
- // supplied as additional entries in the map.
- TYPE_FLAGS = 1<<17
- };
-
- // Enum of localization modes, for use with ATTR_L10N.
- enum {
- L10N_NOT_REQUIRED = 0,
- L10N_SUGGESTED = 1
- };
-
- // This mapping's value.
- Res_value value;
-};
-
-/**
- * Convenience class for accessing data in a ResTable resource.
- */
-class ResTable
-{
-public:
- ResTable();
- ResTable(const void* data, size_t size, void* cookie,
- bool copyData=false);
- ~ResTable();
-
- status_t add(const void* data, size_t size, void* cookie,
- bool copyData=false, const void* idmap = NULL);
- status_t add(Asset* asset, void* cookie,
- bool copyData=false, const void* idmap = NULL);
- status_t add(ResTable* src);
-
- status_t getError() const;
-
- void uninit();
-
- struct resource_name
- {
- const char16_t* package;
- size_t packageLen;
- const char16_t* type;
- size_t typeLen;
- const char16_t* name;
- size_t nameLen;
- };
-
- bool getResourceName(uint32_t resID, resource_name* outName) const;
-
- /**
- * Retrieve the value of a resource. If the resource is found, returns a
- * value >= 0 indicating the table it is in (for use with
- * getTableStringBlock() and getTableCookie()) and fills in 'outValue'. If
- * not found, returns a negative error code.
- *
- * Note that this function does not do reference traversal. If you want
- * to follow references to other resources to get the "real" value to
- * use, you need to call resolveReference() after this function.
- *
- * @param resID The desired resoruce identifier.
- * @param outValue Filled in with the resource data that was found.
- *
- * @return ssize_t Either a >= 0 table index or a negative error code.
- */
- ssize_t getResource(uint32_t resID, Res_value* outValue, bool mayBeBag = false,
- uint16_t density = 0,
- uint32_t* outSpecFlags = NULL,
- ResTable_config* outConfig = NULL) const;
-
- inline ssize_t getResource(const ResTable_ref& res, Res_value* outValue,
- uint32_t* outSpecFlags=NULL) const {
- return getResource(res.ident, outValue, false, 0, outSpecFlags, NULL);
- }
-
- ssize_t resolveReference(Res_value* inOutValue,
- ssize_t blockIndex,
- uint32_t* outLastRef = NULL,
- uint32_t* inoutTypeSpecFlags = NULL,
- ResTable_config* outConfig = NULL) const;
-
- enum {
- TMP_BUFFER_SIZE = 16
- };
- const char16_t* valueToString(const Res_value* value, size_t stringBlock,
- char16_t tmpBuffer[TMP_BUFFER_SIZE],
- size_t* outLen);
-
- struct bag_entry {
- ssize_t stringBlock;
- ResTable_map map;
- };
-
- /**
- * Retrieve the bag of a resource. If the resoruce is found, returns the
- * number of bags it contains and 'outBag' points to an array of their
- * values. If not found, a negative error code is returned.
- *
- * Note that this function -does- do reference traversal of the bag data.
- *
- * @param resID The desired resource identifier.
- * @param outBag Filled inm with a pointer to the bag mappings.
- *
- * @return ssize_t Either a >= 0 bag count of negative error code.
- */
- ssize_t lockBag(uint32_t resID, const bag_entry** outBag) const;
-
- void unlockBag(const bag_entry* bag) const;
-
- void lock() const;
-
- ssize_t getBagLocked(uint32_t resID, const bag_entry** outBag,
- uint32_t* outTypeSpecFlags=NULL) const;
-
- void unlock() const;
-
- class Theme {
- public:
- Theme(const ResTable& table);
- ~Theme();
-
- inline const ResTable& getResTable() const { return mTable; }
-
- status_t applyStyle(uint32_t resID, bool force=false);
- status_t setTo(const Theme& other);
-
- /**
- * Retrieve a value in the theme. If the theme defines this
- * value, returns a value >= 0 indicating the table it is in
- * (for use with getTableStringBlock() and getTableCookie) and
- * fills in 'outValue'. If not found, returns a negative error
- * code.
- *
- * Note that this function does not do reference traversal. If you want
- * to follow references to other resources to get the "real" value to
- * use, you need to call resolveReference() after this function.
- *
- * @param resID A resource identifier naming the desired theme
- * attribute.
- * @param outValue Filled in with the theme value that was
- * found.
- *
- * @return ssize_t Either a >= 0 table index or a negative error code.
- */
- ssize_t getAttribute(uint32_t resID, Res_value* outValue,
- uint32_t* outTypeSpecFlags = NULL) const;
-
- /**
- * This is like ResTable::resolveReference(), but also takes
- * care of resolving attribute references to the theme.
- */
- ssize_t resolveAttributeReference(Res_value* inOutValue,
- ssize_t blockIndex, uint32_t* outLastRef = NULL,
- uint32_t* inoutTypeSpecFlags = NULL,
- ResTable_config* inoutConfig = NULL) const;
-
- void dumpToLog() const;
-
- private:
- Theme(const Theme&);
- Theme& operator=(const Theme&);
-
- struct theme_entry {
- ssize_t stringBlock;
- uint32_t typeSpecFlags;
- Res_value value;
- };
- struct type_info {
- size_t numEntries;
- theme_entry* entries;
- };
- struct package_info {
- size_t numTypes;
- type_info types[];
- };
-
- void free_package(package_info* pi);
- package_info* copy_package(package_info* pi);
-
- const ResTable& mTable;
- package_info* mPackages[Res_MAXPACKAGE];
- };
-
- void setParameters(const ResTable_config* params);
- void getParameters(ResTable_config* params) const;
-
- // Retrieve an identifier (which can be passed to getResource)
- // for a given resource name. The 'name' can be fully qualified
- // (<package>:<type>.<basename>) or the package or type components
- // can be dropped if default values are supplied here.
- //
- // Returns 0 if no such resource was found, else a valid resource ID.
- uint32_t identifierForName(const char16_t* name, size_t nameLen,
- const char16_t* type = 0, size_t typeLen = 0,
- const char16_t* defPackage = 0,
- size_t defPackageLen = 0,
- uint32_t* outTypeSpecFlags = NULL) const;
-
- static bool expandResourceRef(const uint16_t* refStr, size_t refLen,
- String16* outPackage,
- String16* outType,
- String16* outName,
- const String16* defType = NULL,
- const String16* defPackage = NULL,
- const char** outErrorMsg = NULL,
- bool* outPublicOnly = NULL);
-
- static bool stringToInt(const char16_t* s, size_t len, Res_value* outValue);
- static bool stringToFloat(const char16_t* s, size_t len, Res_value* outValue);
-
- // Used with stringToValue.
- class Accessor
- {
- public:
- inline virtual ~Accessor() { }
-
- virtual uint32_t getCustomResource(const String16& package,
- const String16& type,
- const String16& name) const = 0;
- virtual uint32_t getCustomResourceWithCreation(const String16& package,
- const String16& type,
- const String16& name,
- const bool createIfNeeded = false) = 0;
- virtual uint32_t getRemappedPackage(uint32_t origPackage) const = 0;
- virtual bool getAttributeType(uint32_t attrID, uint32_t* outType) = 0;
- virtual bool getAttributeMin(uint32_t attrID, uint32_t* outMin) = 0;
- virtual bool getAttributeMax(uint32_t attrID, uint32_t* outMax) = 0;
- virtual bool getAttributeEnum(uint32_t attrID,
- const char16_t* name, size_t nameLen,
- Res_value* outValue) = 0;
- virtual bool getAttributeFlags(uint32_t attrID,
- const char16_t* name, size_t nameLen,
- Res_value* outValue) = 0;
- virtual uint32_t getAttributeL10N(uint32_t attrID) = 0;
- virtual bool getLocalizationSetting() = 0;
- virtual void reportError(void* accessorCookie, const char* fmt, ...) = 0;
- };
-
- // Convert a string to a resource value. Handles standard "@res",
- // "#color", "123", and "0x1bd" types; performs escaping of strings.
- // The resulting value is placed in 'outValue'; if it is a string type,
- // 'outString' receives the string. If 'attrID' is supplied, the value is
- // type checked against this attribute and it is used to perform enum
- // evaluation. If 'acccessor' is supplied, it will be used to attempt to
- // resolve resources that do not exist in this ResTable. If 'attrType' is
- // supplied, the value will be type checked for this format if 'attrID'
- // is not supplied or found.
- bool stringToValue(Res_value* outValue, String16* outString,
- const char16_t* s, size_t len,
- bool preserveSpaces, bool coerceType,
- uint32_t attrID = 0,
- const String16* defType = NULL,
- const String16* defPackage = NULL,
- Accessor* accessor = NULL,
- void* accessorCookie = NULL,
- uint32_t attrType = ResTable_map::TYPE_ANY,
- bool enforcePrivate = true) const;
-
- // Perform processing of escapes and quotes in a string.
- static bool collectString(String16* outString,
- const char16_t* s, size_t len,
- bool preserveSpaces,
- const char** outErrorMsg = NULL,
- bool append = false);
-
- size_t getBasePackageCount() const;
- const char16_t* getBasePackageName(size_t idx) const;
- uint32_t getBasePackageId(size_t idx) const;
-
- size_t getTableCount() const;
- const ResStringPool* getTableStringBlock(size_t index) const;
- void* getTableCookie(size_t index) const;
-
- // Return the configurations (ResTable_config) that we know about
- void getConfigurations(Vector<ResTable_config>* configs) const;
-
- void getLocales(Vector<String8>* locales) const;
-
- // Generate an idmap.
- //
- // Return value: on success: NO_ERROR; caller is responsible for free-ing
- // outData (using free(3)). On failure, any status_t value other than
- // NO_ERROR; the caller should not free outData.
- status_t createIdmap(const ResTable& overlay, uint32_t originalCrc, uint32_t overlayCrc,
- void** outData, size_t* outSize) const;
-
- enum {
- IDMAP_HEADER_SIZE_BYTES = 3 * sizeof(uint32_t),
- };
- // Retrieve idmap meta-data.
- //
- // This function only requires the idmap header (the first
- // IDMAP_HEADER_SIZE_BYTES) bytes of an idmap file.
- static bool getIdmapInfo(const void* idmap, size_t size,
- uint32_t* pOriginalCrc, uint32_t* pOverlayCrc);
-
-#ifndef HAVE_ANDROID_OS
- void print(bool inclValues) const;
- static String8 normalizeForOutput(const char* input);
-#endif
-
-private:
- struct Header;
- struct Type;
- struct Package;
- struct PackageGroup;
- struct bag_set;
-
- status_t add(const void* data, size_t size, void* cookie,
- Asset* asset, bool copyData, const Asset* idmap);
-
- ssize_t getResourcePackageIndex(uint32_t resID) const;
- ssize_t getEntry(
- const Package* package, int typeIndex, int entryIndex,
- const ResTable_config* config,
- const ResTable_type** outType, const ResTable_entry** outEntry,
- const Type** outTypeClass) const;
- status_t parsePackage(
- const ResTable_package* const pkg, const Header* const header, uint32_t idmap_id);
-
- void print_value(const Package* pkg, const Res_value& value) const;
-
- mutable Mutex mLock;
-
- status_t mError;
-
- ResTable_config mParams;
-
- // Array of all resource tables.
- Vector<Header*> mHeaders;
-
- // Array of packages in all resource tables.
- Vector<PackageGroup*> mPackageGroups;
-
- // Mapping from resource package IDs to indices into the internal
- // package array.
- uint8_t mPackageMap[256];
-};
-
-} // namespace android
-
-#endif // _LIBS_UTILS_RESOURCE_TYPES_H
diff --git a/include/utils/StreamingZipInflater.h b/include/utils/StreamingZipInflater.h
deleted file mode 100644
index 3ace5d5..0000000
--- a/include/utils/StreamingZipInflater.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __LIBS_STREAMINGZIPINFLATER_H
-#define __LIBS_STREAMINGZIPINFLATER_H
-
-#include <unistd.h>
-#include <inttypes.h>
-#include <zlib.h>
-
-#include <utils/Compat.h>
-
-namespace android {
-
-class StreamingZipInflater {
-public:
- static const size_t INPUT_CHUNK_SIZE = 64 * 1024;
- static const size_t OUTPUT_CHUNK_SIZE = 64 * 1024;
-
- // Flavor that pages in the compressed data from a fd
- StreamingZipInflater(int fd, off64_t compDataStart, size_t uncompSize, size_t compSize);
-
- // Flavor that gets the compressed data from an in-memory buffer
- StreamingZipInflater(class FileMap* dataMap, size_t uncompSize);
-
- ~StreamingZipInflater();
-
- // read 'count' bytes of uncompressed data from the current position. outBuf may
- // be NULL, in which case the data is consumed and discarded.
- ssize_t read(void* outBuf, size_t count);
-
- // seeking backwards requires uncompressing fom the beginning, so is very
- // expensive. seeking forwards only requires uncompressing from the current
- // position to the destination.
- off64_t seekAbsolute(off64_t absoluteInputPosition);
-
-private:
- void initInflateState();
- int readNextChunk();
-
- // where to find the uncompressed data
- int mFd;
- off64_t mInFileStart; // where the compressed data lives in the file
- class FileMap* mDataMap;
-
- z_stream mInflateState;
- bool mStreamNeedsInit;
-
- // output invariants for this asset
- uint8_t* mOutBuf; // output buf for decompressed bytes
- size_t mOutBufSize; // allocated size of mOutBuf
- size_t mOutTotalSize; // total uncompressed size of the blob
-
- // current output state bookkeeping
- off64_t mOutCurPosition; // current position in total offset
- size_t mOutLastDecoded; // last decoded byte + 1 in mOutbuf
- size_t mOutDeliverable; // next undelivered byte of decoded output in mOutBuf
-
- // input invariants
- uint8_t* mInBuf;
- size_t mInBufSize; // allocated size of mInBuf;
- size_t mInTotalSize; // total size of compressed data for this blob
-
- // input state bookkeeping
- size_t mInNextChunkOffset; // offset from start of blob at which the next input chunk lies
- // the z_stream contains state about input block consumption
-};
-
-}
-
-#endif
diff --git a/include/utils/TypeHelpers.h b/include/utils/TypeHelpers.h
index a1663f3..1f2c2d5 100644
--- a/include/utils/TypeHelpers.h
+++ b/include/utils/TypeHelpers.h
@@ -213,6 +213,9 @@ void move_backward_type(TYPE* d, const TYPE* s, size_t n = 1) {
template <typename KEY, typename VALUE>
struct key_value_pair_t {
+ typedef KEY key_t;
+ typedef VALUE value_t;
+
KEY key;
VALUE value;
key_value_pair_t() { }
@@ -222,27 +225,64 @@ struct key_value_pair_t {
inline bool operator < (const key_value_pair_t& o) const {
return strictly_order_type(key, o.key);
}
+ inline const KEY& getKey() const {
+ return key;
+ }
+ inline const VALUE& getValue() const {
+ return value;
+ }
};
-template<>
template <typename K, typename V>
struct trait_trivial_ctor< key_value_pair_t<K, V> >
{ enum { value = aggregate_traits<K,V>::has_trivial_ctor }; };
-template<>
template <typename K, typename V>
struct trait_trivial_dtor< key_value_pair_t<K, V> >
{ enum { value = aggregate_traits<K,V>::has_trivial_dtor }; };
-template<>
template <typename K, typename V>
struct trait_trivial_copy< key_value_pair_t<K, V> >
{ enum { value = aggregate_traits<K,V>::has_trivial_copy }; };
-template<>
template <typename K, typename V>
struct trait_trivial_move< key_value_pair_t<K, V> >
{ enum { value = aggregate_traits<K,V>::has_trivial_move }; };
// ---------------------------------------------------------------------------
+/*
+ * Hash codes.
+ */
+typedef uint32_t hash_t;
+
+template <typename TKey>
+hash_t hash_type(const TKey& key);
+
+/* Built-in hash code specializations.
+ * Assumes pointers are 32bit. */
+#define ANDROID_INT32_HASH(T) \
+ template <> inline hash_t hash_type(const T& value) { return hash_t(value); }
+#define ANDROID_INT64_HASH(T) \
+ template <> inline hash_t hash_type(const T& value) { \
+ return hash_t((value >> 32) ^ value); }
+#define ANDROID_REINTERPRET_HASH(T, R) \
+ template <> inline hash_t hash_type(const T& value) { \
+ return hash_type(*reinterpret_cast<const R*>(&value)); }
+
+ANDROID_INT32_HASH(bool)
+ANDROID_INT32_HASH(int8_t)
+ANDROID_INT32_HASH(uint8_t)
+ANDROID_INT32_HASH(int16_t)
+ANDROID_INT32_HASH(uint16_t)
+ANDROID_INT32_HASH(int32_t)
+ANDROID_INT32_HASH(uint32_t)
+ANDROID_INT64_HASH(int64_t)
+ANDROID_INT64_HASH(uint64_t)
+ANDROID_REINTERPRET_HASH(float, uint32_t)
+ANDROID_REINTERPRET_HASH(double, uint64_t)
+
+template <typename T> inline hash_t hash_type(const T*& value) {
+ return hash_type(uintptr_t(value));
+}
+
}; // namespace android
// ---------------------------------------------------------------------------
diff --git a/include/utils/ZipFileCRO.h b/include/utils/ZipFileCRO.h
deleted file mode 100644
index 3e42a95..0000000
--- a/include/utils/ZipFileCRO.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//
-// C API for ead-only access to Zip archives, with minimal heap allocation.
-//
-#ifndef __LIBS_ZIPFILECRO_H
-#define __LIBS_ZIPFILECRO_H
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-#include <utils/Compat.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * Trivial typedef to ensure that ZipFileCRO is not treated as a simple integer.
- */
-typedef void* ZipFileCRO;
-
-/*
- * Trivial typedef to ensure that ZipEntryCRO is not treated as a simple
- * integer. We use NULL to indicate an invalid value.
- */
-typedef void* ZipEntryCRO;
-
-extern ZipFileCRO ZipFileXRO_open(const char* path);
-
-extern void ZipFileCRO_destroy(ZipFileCRO zip);
-
-extern ZipEntryCRO ZipFileCRO_findEntryByName(ZipFileCRO zip,
- const char* fileName);
-
-extern bool ZipFileCRO_getEntryInfo(ZipFileCRO zip, ZipEntryCRO entry,
- int* pMethod, size_t* pUncompLen,
- size_t* pCompLen, off64_t* pOffset, long* pModWhen, long* pCrc32);
-
-extern bool ZipFileCRO_uncompressEntry(ZipFileCRO zip, ZipEntryCRO entry, int fd);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /*__LIBS_ZIPFILECRO_H*/
diff --git a/include/utils/ZipFileRO.h b/include/utils/ZipFileRO.h
deleted file mode 100644
index 547e36a..0000000
--- a/include/utils/ZipFileRO.h
+++ /dev/null
@@ -1,262 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * Read-only access to Zip archives, with minimal heap allocation.
- *
- * This is similar to the more-complete ZipFile class, but no attempt
- * has been made to make them interchangeable. This class operates under
- * a very different set of assumptions and constraints.
- *
- * One such assumption is that if you're getting file descriptors for
- * use with this class as a child of a fork() operation, you must be on
- * a pread() to guarantee correct operation. This is because pread() can
- * atomically read at a file offset without worrying about a lock around an
- * lseek() + read() pair.
- */
-#ifndef __LIBS_ZIPFILERO_H
-#define __LIBS_ZIPFILERO_H
-
-#include <utils/Compat.h>
-#include <utils/Errors.h>
-#include <utils/FileMap.h>
-#include <utils/threads.h>
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <time.h>
-
-namespace android {
-
-/*
- * Trivial typedef to ensure that ZipEntryRO is not treated as a simple
- * integer. We use NULL to indicate an invalid value.
- */
-typedef void* ZipEntryRO;
-
-/*
- * Open a Zip archive for reading.
- *
- * We want "open" and "find entry by name" to be fast operations, and we
- * want to use as little memory as possible. We memory-map the file,
- * and load a hash table with pointers to the filenames (which aren't
- * null-terminated). The other fields are at a fixed offset from the
- * filename, so we don't need to extract those (but we do need to byte-read
- * and endian-swap them every time we want them).
- *
- * To speed comparisons when doing a lookup by name, we could make the mapping
- * "private" (copy-on-write) and null-terminate the filenames after verifying
- * the record structure. However, this requires a private mapping of
- * every page that the Central Directory touches. Easier to tuck a copy
- * of the string length into the hash table entry.
- *
- * NOTE: If this is used on file descriptors inherited from a fork() operation,
- * you must be on a platform that implements pread() to guarantee correctness
- * on the shared file descriptors.
- */
-class ZipFileRO {
-public:
- ZipFileRO()
- : mFd(-1), mFileName(NULL), mFileLength(-1),
- mDirectoryMap(NULL),
- mNumEntries(-1), mDirectoryOffset(-1),
- mHashTableSize(-1), mHashTable(NULL)
- {}
-
- ~ZipFileRO();
-
- /*
- * Open an archive.
- */
- status_t open(const char* zipFileName);
-
- /*
- * Find an entry, by name. Returns the entry identifier, or NULL if
- * not found.
- *
- * If two entries have the same name, one will be chosen at semi-random.
- */
- ZipEntryRO findEntryByName(const char* fileName) const;
-
- /*
- * Return the #of entries in the Zip archive.
- */
- int getNumEntries(void) const {
- return mNumEntries;
- }
-
- /*
- * Return the Nth entry. Zip file entries are not stored in sorted
- * order, and updated entries may appear at the end, so anyone walking
- * the archive needs to avoid making ordering assumptions. We take
- * that further by returning the Nth non-empty entry in the hash table
- * rather than the Nth entry in the archive.
- *
- * Valid values are [0..numEntries).
- *
- * [This is currently O(n). If it needs to be fast we can allocate an
- * additional data structure or provide an iterator interface.]
- */
- ZipEntryRO findEntryByIndex(int idx) const;
-
- /*
- * Copy the filename into the supplied buffer. Returns 0 on success,
- * -1 if "entry" is invalid, or the filename length if it didn't fit. The
- * length, and the returned string, include the null-termination.
- */
- int getEntryFileName(ZipEntryRO entry, char* buffer, int bufLen) const;
-
- /*
- * Get the vital stats for an entry. Pass in NULL pointers for anything
- * you don't need.
- *
- * "*pOffset" holds the Zip file offset of the entry's data.
- *
- * Returns "false" if "entry" is bogus or if the data in the Zip file
- * appears to be bad.
- */
- bool getEntryInfo(ZipEntryRO entry, int* pMethod, size_t* pUncompLen,
- size_t* pCompLen, off64_t* pOffset, long* pModWhen, long* pCrc32) const;
-
- /*
- * Create a new FileMap object that maps a subset of the archive. For
- * an uncompressed entry this effectively provides a pointer to the
- * actual data, for a compressed entry this provides the input buffer
- * for inflate().
- */
- FileMap* createEntryFileMap(ZipEntryRO entry) const;
-
- /*
- * Uncompress the data into a buffer. Depending on the compression
- * format, this is either an "inflate" operation or a memcpy.
- *
- * Use "uncompLen" from getEntryInfo() to determine the required
- * buffer size.
- *
- * Returns "true" on success.
- */
- bool uncompressEntry(ZipEntryRO entry, void* buffer) const;
-
- /*
- * Uncompress the data to an open file descriptor.
- */
- bool uncompressEntry(ZipEntryRO entry, int fd) const;
-
- /* Zip compression methods we support */
- enum {
- kCompressStored = 0, // no compression
- kCompressDeflated = 8, // standard deflate
- };
-
- /*
- * Utility function: uncompress deflated data, buffer to buffer.
- */
- static bool inflateBuffer(void* outBuf, const void* inBuf,
- size_t uncompLen, size_t compLen);
-
- /*
- * Utility function: uncompress deflated data, buffer to fd.
- */
- static bool inflateBuffer(int fd, const void* inBuf,
- size_t uncompLen, size_t compLen);
-
- /*
- * Utility function to convert ZIP's time format to a timespec struct.
- */
- static inline void zipTimeToTimespec(long when, struct tm* timespec) {
- const long date = when >> 16;
- timespec->tm_year = ((date >> 9) & 0x7F) + 80; // Zip is years since 1980
- timespec->tm_mon = (date >> 5) & 0x0F;
- timespec->tm_mday = date & 0x1F;
-
- timespec->tm_hour = (when >> 11) & 0x1F;
- timespec->tm_min = (when >> 5) & 0x3F;
- timespec->tm_sec = (when & 0x1F) << 1;
- }
-
- /*
- * Some basic functions for raw data manipulation. "LE" means
- * Little Endian.
- */
- static inline unsigned short get2LE(const unsigned char* buf) {
- return buf[0] | (buf[1] << 8);
- }
- static inline unsigned long get4LE(const unsigned char* buf) {
- return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
- }
-
-private:
- /* these are private and not defined */
- ZipFileRO(const ZipFileRO& src);
- ZipFileRO& operator=(const ZipFileRO& src);
-
- /* locate and parse the central directory */
- bool mapCentralDirectory(void);
-
- /* parse the archive, prepping internal structures */
- bool parseZipArchive(void);
-
- /* add a new entry to the hash table */
- void addToHash(const char* str, int strLen, unsigned int hash);
-
- /* compute string hash code */
- static unsigned int computeHash(const char* str, int len);
-
- /* convert a ZipEntryRO back to a hash table index */
- int entryToIndex(const ZipEntryRO entry) const;
-
- /*
- * One entry in the hash table.
- */
- typedef struct HashEntry {
- const char* name;
- unsigned short nameLen;
- //unsigned int hash;
- } HashEntry;
-
- /* open Zip archive */
- int mFd;
-
- /* Lock for handling the file descriptor (seeks, etc) */
- mutable Mutex mFdLock;
-
- /* zip file name */
- char* mFileName;
-
- /* length of file */
- size_t mFileLength;
-
- /* mapped file */
- FileMap* mDirectoryMap;
-
- /* number of entries in the Zip archive */
- int mNumEntries;
-
- /* CD directory offset in the Zip archive */
- off64_t mDirectoryOffset;
-
- /*
- * We know how many entries are in the Zip archive, so we have a
- * fixed-size hash table. We probe for an empty slot.
- */
- int mHashTableSize;
- HashEntry* mHashTable;
-};
-
-}; // namespace android
-
-#endif /*__LIBS_ZIPFILERO_H*/
diff --git a/include/utils/ZipUtils.h b/include/utils/ZipUtils.h
deleted file mode 100644
index 42c42b6..0000000
--- a/include/utils/ZipUtils.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//
-// Miscellaneous zip/gzip utility functions.
-//
-#ifndef __LIBS_ZIPUTILS_H
-#define __LIBS_ZIPUTILS_H
-
-#include <stdio.h>
-
-namespace android {
-
-/*
- * Container class for utility functions, primarily for namespace reasons.
- */
-class ZipUtils {
-public:
- /*
- * General utility function for uncompressing "deflate" data from a file
- * to a buffer.
- */
- static bool inflateToBuffer(int fd, void* buf, long uncompressedLen,
- long compressedLen);
- static bool inflateToBuffer(FILE* fp, void* buf, long uncompressedLen,
- long compressedLen);
-
- /*
- * Someday we might want to make this generic and handle bzip2 ".bz2"
- * files too.
- *
- * We could declare gzip to be a sub-class of zip that has exactly
- * one always-compressed entry, but we currently want to treat Zip
- * and gzip as distinct, so there's no value.
- *
- * The zlib library has some gzip utilities, but it has no interface
- * for extracting the uncompressed length of the file (you do *not*
- * want to gzseek to the end).
- *
- * Pass in a seeked file pointer for the gzip file. If this is a gzip
- * file, we set our return values appropriately and return "true" with
- * the file seeked to the start of the compressed data.
- */
- static bool examineGzip(FILE* fp, int* pCompressionMethod,
- long* pUncompressedLen, long* pCompressedLen, unsigned long* pCRC32);
-
-private:
- ZipUtils() {}
- ~ZipUtils() {}
-};
-
-}; // namespace android
-
-#endif /*__LIBS_ZIPUTILS_H*/
diff --git a/include/utils/threads.h b/include/utils/threads.h
index ab3e8cd..b4a8b7c 100644
--- a/include/utils/threads.h
+++ b/include/utils/threads.h
@@ -526,6 +526,12 @@ public:
// Do not call from this object's thread; will return WOULD_BLOCK in that case.
status_t join();
+#ifdef HAVE_ANDROID_OS
+ // Return the thread's kernel ID, same as the thread itself calling gettid() or
+ // androidGetTid(), or -1 if the thread is not running.
+ pid_t getTid() const;
+#endif
+
protected:
// exitPending() returns true if requestExit() has been called.
bool exitPending() const;
@@ -551,8 +557,10 @@ private:
volatile bool mExitPending;
volatile bool mRunning;
sp<Thread> mHoldSelf;
-#if HAVE_ANDROID_OS
- int mTid;
+#ifdef HAVE_ANDROID_OS
+ // legacy for debugging, not used by getTid() as it is set by the child thread
+ // and so is not initialized until the child reaches that point
+ pid_t mTid;
#endif
};